LeetCode刷题:231.Power of Two


231. Power of Two

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

解题思路:

通过观察可知,如果一个数字为2的幂,那么这个数字中的二进制数中的最高位必为1,其它都为0,那么令其减1,最高位变为0,其它位变为1。例如23=8,其二进制形式为1000,那么8 - 1 = 7,7的二进制形式为0111,1000 & 0111 = 0;我们可以通过这个性质来判断该数字是否为2的幂。

解答:
class Solution {
public:
    bool isPowerOfTwo(int n) {
        return (n > 0) && (! (n & (n - 1) ) );
    }
};

文章作者: Jason
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Jason !
  目录