[leetcode] Power of Two


Power of Two

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

//can n be negative?
//negative number is definitely not a power of two
//1 is power of 2
//0 is not


//1 2 4 8 16 32 64 ..
class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n <= 0) return false;
        if(n == 1) return true;
        int m = 1;
        //30 times
        for(int i = 1; i < 31; i++){
            m = m << 1;
            if(m == n) return true;
        }
        return false;
    }
};

Untitled

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.