LeetCode题解:Power of Two
2015-08-12 10:47
113 查看
Given an integer, write a function to determine if it is a power of two.
题意:给定一个整数,判断是否为2的幂
解决思路:如果一个整数n是2的幂,那么让n和n-1进行与运算必然为0(位运算)
代码:
题意:给定一个整数,判断是否为2的幂
解决思路:如果一个整数n是2的幂,那么让n和n-1进行与运算必然为0(位运算)
代码:
public boolean isPowerOfTwo(int n) { return ((n & (n-1))==0 && n>0); }