using System;
namespace Articulos.Preguntas.P0720
{
public sealed class ComprobacionPotenciaDe2
{
public static void Main()
{
ulong numero = 8;
bool esPotenciaDe2 = false;
esPotenciaDe2 = EsPotenciaDe2 (numero);
Console.WriteLine ("\n{0} {1}es potencia de 2.",
numero.ToString (),
esPotenciaDe2 ? " " : "no "
);
numero = 11;
esPotenciaDe2 = EsPotenciaDe2 (numero);
Console.WriteLine ("\n{0} {1}es potencia de 2.\n",
numero.ToString (),
esPotenciaDe2 ? " " : "no "
);
}
// Este método comprueba que un número entero de 64
// bits sin signo (ulong) es potencia de 2:
private static bool EsPotenciaDe2(ulong numero)
{
// Primero comprueba que es distinto de 0,
// luego resta una unidad del número `numero`
// realiza la operación bitwise AND, finalmente
// comprueba que sea igual a 0;
// == 0 -> true
// != 0 -> false
return ((numero != 0) && ((numero & (numero - 1)) == 0));
}
}
}
dXNpbmcgU3lzdGVtOwoKbmFtZXNwYWNlIEFydGljdWxvcy5QcmVndW50YXMuUDA3MjAKewogICAgcHVibGljIHNlYWxlZCBjbGFzcyBDb21wcm9iYWNpb25Qb3RlbmNpYURlMgogICAgewogICAgICAgIHB1YmxpYyBzdGF0aWMgdm9pZCBNYWluKCkKICAgICAgICB7CiAgICAgICAgICAgIHVsb25nIG51bWVybyA9IDg7CiAgICAgICAgICAgIGJvb2wgZXNQb3RlbmNpYURlMiA9IGZhbHNlOwogICAgICAgICAgICAKICAgICAgICAgICAgZXNQb3RlbmNpYURlMiA9IEVzUG90ZW5jaWFEZTIgKG51bWVybyk7CiAgICAgICAgICAgIAogICAgICAgICAgICBDb25zb2xlLldyaXRlTGluZSAoIlxuezB9IHsxfWVzIHBvdGVuY2lhIGRlIDIuIiwgCiAgICAgICAgICAgICAgICBudW1lcm8uVG9TdHJpbmcgKCksIAogICAgICAgICAgICAgICAgZXNQb3RlbmNpYURlMiA/ICIgIiA6ICJubyAiCiAgICAgICAgICAgICk7CiAgICAgICAgICAgIAogICAgICAgICAgICBudW1lcm8gPSAxMTsKICAgICAgICAgICAgCiAgICAgICAgICAgIGVzUG90ZW5jaWFEZTIgPSBFc1BvdGVuY2lhRGUyIChudW1lcm8pOwogICAgICAgICAgICAKICAgICAgICAgICAgQ29uc29sZS5Xcml0ZUxpbmUgKCJcbnswfSB7MX1lcyBwb3RlbmNpYSBkZSAyLlxuIiwgCiAgICAgICAgICAgICAgICBudW1lcm8uVG9TdHJpbmcgKCksIAogICAgICAgICAgICAgICAgZXNQb3RlbmNpYURlMiA/ICIgIiA6ICJubyAiCiAgICAgICAgICAgICk7CiAgICAgICAgfQogICAgICAgIAogICAgICAgIC8vIEVzdGUgbcOpdG9kbyBjb21wcnVlYmEgcXVlIHVuIG7Dum1lcm8gZW50ZXJvIGRlIDY0IAogICAgICAgIC8vIGJpdHMgc2luIHNpZ25vICh1bG9uZykgZXMgcG90ZW5jaWEgZGUgMjoKICAgICAgICBwcml2YXRlIHN0YXRpYyBib29sIEVzUG90ZW5jaWFEZTIodWxvbmcgbnVtZXJvKQogICAgICAgIHsKICAgICAgICAgICAgLy8gUHJpbWVybyBjb21wcnVlYmEgcXVlIGVzIGRpc3RpbnRvIGRlIDAsIAogICAgICAgICAgICAvLyBsdWVnbyByZXN0YSB1bmEgdW5pZGFkIGRlbCBuw7ptZXJvIGBudW1lcm9gIAogICAgICAgICAgICAvLyByZWFsaXphIGxhIG9wZXJhY2nDs24gYml0d2lzZSBBTkQsIGZpbmFsbWVudGUgCiAgICAgICAgICAgIC8vIGNvbXBydWViYSBxdWUgc2VhIGlndWFsIGEgMDsKICAgICAgICAgICAgLy8gPT0gMCAtPiB0cnVlCiAgICAgICAgICAgIC8vICE9IDAgLT4gZmFsc2UKICAgICAgICAgICAgcmV0dXJuICgobnVtZXJvICE9IDApICYmICgobnVtZXJvICYgKG51bWVybyAtIDEpKSA9PSAwKSk7CiAgICAgICAgfQogICAgfQp9