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

Subject to the effect :

   Determining whether an integer power of two.

Understanding:

   A power of 2 binary representation, only one is 1, and the remaining bits are all 0. Locate the first number 1 to determine whether the remaining bits 0.

Code 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;
    }
};

operation result:

  When execution: 4 ms, beat the 92.62% of all users to submit in C ++

  Memory consumption: 8.2 MB, beat the 5.71% of all users to submit in C ++

Guess you like

Origin www.cnblogs.com/lpomeloz/p/11022445.html