码迷,mamicode.com
首页 > 其他好文 > 详细

Power of Two

时间:2015-07-17 21:08:41      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

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

[思路]

1)考虑各种边界情况。输入是整型值,说明不用考虑2的负指数情况。

2)如果一个数是二的倍数,说明他的二进制形式只有一位是1。做好判断即可。

循环判断1的位数解法最容易想到。

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

};


版权声明:本文为博主原创文章,未经博主允许不得转载。

Power of Two

标签:

原文地址:http://blog.csdn.net/ciaoliang/article/details/46931427

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!