首页 > 其他 > 详细

[LeetCode]Power of Two

时间:2018-02-25 12:00:17      阅读:213      评论:0      收藏:0      [点我收藏+]

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

[思路]

1)考虑各种边界情况。

输入是整型值,说明不用考虑2的负指数情况。

2)假设一个数是二的倍数。说明他的二进制形式仅仅有一位是1。做好推断就可以。

循环推断1的位数解法最easy想到。

Leetcode上有种解法,就是让n&n-1,假设n仅仅含有一个1那么结果就是零。

简单解法:

class Solution {
public:
    bool isPowerOfTwo(int n) {
       if(n<=0) return false;
       int count = 0;
       while(n!=0){
           if(n%2!=0){
               count++;
           }
           n = n>>1;
           if(count>1)
            return false;
       }
        return true;
    }

};
奇妙解法:

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

};


[LeetCode]Power of Two

原文:https://www.cnblogs.com/zhchoutai/p/8468828.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!