【LeetCode】Power of Two

问题描写叙述

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

原文地址:https://www.cnblogs.com/mengfanrong/p/5425129.html