[刷题防痴呆] 0342 - 4的幂 (Power of Fou

2021-11-01  本文已影响0人  西出玉门东望长安

题目地址

https://leetcode.com/problems/power-of-four/description/

题目描述

342. Power of Four

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example 1:

Input: 16
Output: true
Example 2:

Input: 5
Output: false

思路

关键点

代码

// 递归
class Solution {
    public boolean isPowerOfFour(int num) {
        if (num < 1) {
            return false;
        }
        
        while (num % 4 == 0) {
            num /= 4;
        }
        return num == 1;
    }
}

// 位运算
class Solution {
    public boolean isPowerOfFour(int n) {
        return n > 0 && (n & (n - 1)) == 0 && n % 3 == 1;
    }
}
上一篇下一篇

猜你喜欢

热点阅读