标签:2的幂数 power-of-2 leetcode java
Given an integer, write a function to determine if it is a power of two.
意:判断一个数是否是2的n次幂
如果一个数小于或等于0,一定不是2的幂次数
如果一个大于0且数是2的n次幂,则其的二进制形式有且仅有一个1,反之成立。
public class Solution {
public boolean isPowerOfTwo(int n) {
if(n<=0)
return false;
int i = 0;
int countBit = 0;
while(i < 32){
if((n&(1<<i))!=0)
countBit++;
i++;
}
if(countBit != 1)
return false;
return true;
}
}
T(n)=O(1)
public static void main(String [] args){
int n = 4;
Solution s = new Solution();
System.out.println(s.isPowerOfTwo(n));
}
true
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:2的幂数 power-of-2 leetcode java
原文地址:http://blog.csdn.net/baidu_22502417/article/details/46773387