您的位置:首页 > 其它

LeetCode 231. Power of Two(2的N次幂)

2016-04-05 11:37 295 查看
原题网址:https://leetcode.com/problems/power-of-two/

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

思路:数字n是2的整数次幂,当且仅当n的二进制表示有且只有一个1。

方法一:直接统计1比特数。

public class Solution {
public boolean isPowerOfTwo(int n) {
int count = 0;
for(;n>0 && count<=1; count += (n&1), n>>=1);
return count == 1;
}
}


方法二:直接获取最低位1比特。

public class Solution {
public boolean isPowerOfTwo(int n) {
return n>0 && n == (n & -n);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: