【Leetcode231】Power of Two

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n < 1)
            return false;
        // while(n%2 == 0){
        //     n /= 2;
        // }
        // return n==1;
        return(!(n & (n-1)));
    }
};

首先说如果从1一次次的乘以2是不可取的,因为虽然n可以用int表示,但是总有一次要超过这个n才终止,而这个n很有可能特别大。

我的做法是向下除,除到只剩下1为止。

借鉴了一种做法,直接从二进制上想办法,位操作,骚

发布了112 篇原创文章 · 获赞 15 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_39458342/article/details/104726636
今日推荐