原题;
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example 1:
Input: 16 Output: trueExample 2:
Input: 5 Output: falseFollow up: Could you solve it without loops/recursion?
和上一道题一样,判断是不是4的幂,先用循环:
Success
Runtime: 4 ms, faster than 80.82% of C++ online submissions for Power of Four.
Memory Usage: 7.9 MB, less than 92.47% of C++ online submissions for Power of Four.
代码:
class Solution {
public:
bool isPowerOfFour(int num) {
if(!num){return 0;}
while(num%4==0){
num/=4;
}
if(num==1){return 1;}
return 0;
}
};
再用log:
Success
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Power of Four.
Memory Usage: 8.3 MB, less than 9.06% of C++ online submissions for Power of Four.