[leetcode] 342. Power of Four 解题报告

题目链接:https://leetcode.com/problems/power-of-four/

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

Example:
Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?


思路: recursive 的比较好写, 不用loop的难想一些

class Solution {
public:
    bool isPowerOfFour(int num) {
        if(num == 1) return true;
        if(num%2==1) return false;
        if(num <= 0) return false;
        if(num%4 != 0) return false;
        if(num/4==1) return true;
        return isPowerOfFour(num/4);
    }
};


class Solution {
public:
    bool isPowerOfFour(int num) {
        if(num <= 0) return false;
        if(num & num-1) return false;
        return num % 3 == 1;
    }
};
第二种参考:https://leetcode.com/discuss/99877/my-non-loop-solution-with-no-relation-to-the-bit-length-of-int


你可能感兴趣的:(LeetCode,Math)