题目
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
位运算
【leetcode】-191. Number of 1 Bits 有用到n&(n-1)来消除二进制中的最后一个1。
这题判断n是否为2的指数。如果一个数是2的指数,那么其二进制表示中一定只含有一个1。
例如:
2^0 = 1 = 0b0001
2^1 = 2 = 0b0010
2^2 = 4 = 0b0100
所以如果消除最后1后为0就表示该数是2的指数。
Java
class Solution {
public boolean isPowerOfTwo(int n) {
if(n<=0)
return false;
return (n&(n-1))==0;
}
}