# C#LeetCode刷题之#231-2的幂（Power of Two）

Given an integer, write a function to determine if it is a power of two.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

```public class Program {

public static void Main(string[] args) {
var n = 8;
var res = IsPowerOfTwo(n);
Console.WriteLine(res);

n = 513;
res = IsPowerOfTwo2(n);
Console.WriteLine(res);

}

private static bool IsPowerOfTwo(int n) {
//先看原值是否能被2整除
//若不能整除，不是2的幂；
//若能整除，继续往下，直接<=1时为止
//最后判断值是否为1即可
while(n % 2 == 0 && (n /= 2) > 1) { }
return n == 1;
}

private static bool IsPowerOfTwo2(int n) {
//2为10,4为100
//2-1为01,4-1为011
//对它们进行“与”运算
//10 & 01 = 0
//100 & 011 = 0
//得出结论，如果一个数n为2的幂，则n & (n - 1) = 0
return ((n > 0) && (n & (n - 1)) == 0);
}

}```

```True
False```