【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,反之成立。markdown

算法實現

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)spa

演示結果

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

truecode

相關文章
相關標籤/搜索