首页 > 其他 > 详细

【LeetCode】Power of Two

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

问题描述

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

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

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