卖萌的弱渣

I am stupid, I am hungry.

Power of Two

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

Solution

如果一个整数是2的幂,那么它的二进制形式最高位为1,其余各位为0

等价于:n & (n - 1) = 0,且n > 0

  • Java
(Power-of-Two.java) download
1
2
3
4
5
public class Solution {
    public boolean isPowerOfTwo(int n) {
        return (n>0 && (n&(n-1))==0);
    }
}
  • Python
(Power-of-Two.py) download
1
2
3
4
5
6
7
8
class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """

        return n > 0 and n & (n-1) == 0