[leetcode]342. Power of Four
阿新 • • 發佈:2018-12-04
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.
分析:
和判斷一個數是否為3的冪類似,可以用迴圈/4判斷餘數或者利用對數來判斷,程式碼如下:
解法1:
class Solution { public: bool isPowerOfFour(int num) { if(num <= 0) return false; if(num == 1) return true; while(num/4 != 1) { if(num%4 != 0) return false; else num /= 4; } if(num % 4 == 0) return true; else return false; } };
解法2:
class Solution {
public:
bool isPowerOfThree(int num) {
if(num <= 0)
return false;
if(int(log10(num)/log10(4)) - log10(num)/log10(4) == 0)
return true;
else
return false;
}
};