342. Power of Four
Problem:
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
Follow up: Could you solve it without loops/recursion?
思路:
Solution (C++):
bool isPowerOfFour(int num) {
if (num <= 0) return false;
while (num%4 == 0) num /= 4;
if (num == 1) return true;
else return false;
}
性能:
Runtime: 4 ms Memory Usage: 6 MB
思路:
Solution (C++):
bool isPowerOfFour(int num) {
return (num > 0) && (num & (num-1)) == 0 && (num-1)%3 == 0;
}
性能:
Runtime: 0 ms Memory Usage: 5.9 MB
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。