【Power of Two】cpp

题目:

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

代码:

class Solution {
public:
    bool isPowerOfTwo(int n) {
            if ( n<=0 ) return false;
            int countOne = 0;
            for ( int i=0; i<sizeof(n)*8 && countOne<=1; ++i )
            {
                countOne += (n>>i) & 1;
            }
            return countOne==1;
    }
};

tips:

首先的思路是bit-munipulation

检查int中有多少个1

学习了一个更简洁的(https://leetcode.com/discuss/45017/5-lines-o-1-space%26time-c-solution-no-hash

自己优化了一下 一行代码AC。

class Solution {
public:
    bool isPowerOfTwo(int n) {
            return  n<=0 ? false : !(n & (n-1));
    }
};

 

posted on 2015-07-22 07:23  承续缘  阅读(281)  评论(0编辑  收藏  举报

导航