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

【LeetCode】Power of Two

时间:2015-07-06 14:14:31      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:2的幂数   power-of-2   leetcode   java   

问题描述

Given an integer, write a function to determine if it is a power of two.
意:判断一个数是否是2的n次幂

算法思想

如果一个数小于或等于0,一定不是2的幂次数
如果一个大于0且数是2的n次幂,则其的二进制形式有且仅有一个1,反之成立。

算法实现

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if(n<=0)
            return false;
        int i = 0;
        int countBit = 0;
        while(i < 32){
            if((n&(1<<i))!=0)
                countBit++;
            i++;
        }
        if(countBit != 1)
            return false;
        return true;
    }
}

算法时间

T(n)=O(1)

演示结果

public static void main(String [] args){
        int n = 4;
        Solution s = new Solution();    
        System.out.println(s.isPowerOfTwo(n));
    }

true

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

【LeetCode】Power of Two

标签:2的幂数   power-of-2   leetcode   java   

原文地址:http://blog.csdn.net/baidu_22502417/article/details/46773387

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