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

[leetcode]231.Power of Two

时间:2018-10-14 13:49:06      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:code   OLE   ==   isp   func   题目   个数   一个   leetcode   

题目

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

Example 1:

Input: 1
Output: true
Explanation: 20 = 1
Example 2:

Input: 16
Output: true
Explanation: 24 = 16
Example 3:

Input: 218
Output: false

解法一

思路

就是统计该数字转成二进制以后1的个数,如果只有一个1,说明其为2的幂。

代码

class Solution {
    public boolean isPowerOfTwo(int n) {
        if(n < 0) return false;
        int res = 0;
        for(int i = 0; i < 32; i++) {
            res += (n&1);
            n >>= 1;
        }
        return res == 1;
    }
}

解法二

思路

如果一个数是2的次方数的话,根据上面分析,那么它的二进数必然是最高位为1,其它都为0,那么如果此时我们减1的话,则最高位会降一位,其余为0的位现在都为变为1,那么我们把两数相与,就会得到0,用这个性质也能来解题,而且只需一行代码就可以搞定。

代码

class Solution {
    public boolean isPowerOfTwo(int n) {
        return ((n & (n-1))==0 && n>0);
    }
}

[leetcode]231.Power of Two

标签:code   OLE   ==   isp   func   题目   个数   一个   leetcode   

原文地址:https://www.cnblogs.com/shinjia/p/9785645.html

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