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

leetcode-231-Power of Two

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

标签:leetcode

                                              Power of Two

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

判断给出的数,是否为2的次方,如1,2,4,8,16...




 移位操作,2的次方的数,换位2进制表示,都是第一个为1 ,其后面都是0,。如8=1000

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if (!n) return false; //等于0的情况
        while (n != 1){       // 二进制第一个数肯定是1,不判断
            if (n&1)  return false;  // 为1  则不是2的次方
            n = n >> 1;
        }
        return true;  
    }
};




利用 n&(n - 1)  ,即将二进制的最后一个1变为0

如果是2的次方,则n&(n - 1)=0

class Solution {
public:
    bool isPowerOfTwo(int n) {
        //if (!n) return false; // 有可能是负数,故不行
        if (n <= 0) return false;
        return ( n&(n - 1) )== 0;
    }
};



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

leetcode-231-Power of Two

标签:leetcode

原文地址:http://blog.csdn.net/u014705854/article/details/46931333

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