1. 程式人生 > >LeetCode power of four

LeetCode power of four

boolean 沒有 poweroff 進制 一個數 提交 col pre leetcode

原題目是:判斷一個整數是否是4次冪

這裏提供一種提交記錄裏沒有的解法(2018/10/5)

我們知道如果判斷一個數是否是2的次冪,可以用

num & (num-1) == 0

因為如果是2的次冪,則減一後二進制位都是1

受此啟發,該題這樣做:

class Solution {
    public boolean isPowerOfFour(int num) {
        return num >= 1 && (num&(num-1))==0 && (num-1)%3==0;
    }
}        

因為4的次冪減一後,二進制必有偶數個1,則必然是3的倍數。

LeetCode power of four