342. Power of Four

Easy

Given an integer n, return true if it is a power of four. Otherwise, return false.

An integer n is a power of four, if there exists an integer x such that n == 4x.

Example 1:

Input: n = 16
Output:
 true

Example 2:

Input: n = 5
Output:
 false

Example 3:

Input: n = 1
Output:
 true

Constraints:

  • -231 <= n <= 231 - 1

解題

func isPowerOfFour(n int) bool {
    if n==1 { return true }
    
    for n>0 {
        if n==(n>>2)<<2 { // 判斷是不是有奇數1
            if n>>2==1 {
                return true
            }
        } else { //有的話直接返回false
            return false
        }
        
        n = n>>2
    }
    
    return false
    
}

第二個解法是在討論區看到、覺得最好的解法

const SecondBit int = 0x55555555 //  in binary ...1010101

func isPowerOfFour(n int) bool {
	return n > 0 && // Can't have 0 or negatives
		n&(n-1) == 0 && // Checking if only 1 bit is active
		n&SecondBit != 0 // Checking if the bit is in an odd position
}

Last updated