[leetcode]power of two

题目描述

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

解题思路与代码

一个整数如果是2的整数次方,那么它的二进制表示中有且只有一位是1,而其他所有位都是0。根据分析可知,把一个整数减去1之后再和它自己做与运算,这个整数中唯一的1就会变成0。代码如下:

1
2
3
4
5
6
7
8
9
10
11
public class  {
public boolean isPowerOfTwo1(int n) {
if(n <= 0) return false;
return Integer.bitCount(n) == 1;
}

public boolean isPowerOfTwo(int n) {
if(n <= 0) return false;
return (n & (n-1)) == 0;
}
}