LeetCode 231. Power of Two

来源:互联网 发布:toad for oracle mac 编辑:程序博客网 时间:2024/06/06 05:33

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

分析
如果是power of two, 则2进制表达中,有且仅有一个1. 可以通过移位来数1的个数, 这里用了一个巧妙的办法, 即判断 N & (N-1) 是否为0.

代码

class Solution {public:    bool isPowerOfTwo(int n) {        return n > 0 && ((n & (n -1)) == 0);    }};
0 0
原创粉丝点击