letecode [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的幂次方。

理  解:

   2的幂 的二进制表示中只有一位是1,其余位全是0。找到第一个1判断剩下的数是否位0.

代 码 C++:

class Solution {
public:
    bool isPowerOfTwo(int n) {
        while(n){
            if(n&1==1){
                n = n>>1;
                if(n==0)
                    return true;
                else
                    return false;
            }
            n = n>>1;
        }
        return false;
    }
};

运行结果:

  执行用时 :4 ms, 在所有C++提交中击败了92.62%的用户

  内存消耗 :8.2 MB, 在所有C++提交中击败了5.71%的用户

猜你喜欢

转载自www.cnblogs.com/lpomeloz/p/11022445.html
今日推荐