<LeetCode OJ> 342. Power of Four
2016-04-21 20:52
483 查看
Total Accepted: 4769 Total
Submissions: 14338 Difficulty: Easy
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?
Credits:
Special thanks to @yukuairoy for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Tags
Bit Manipulation
Show Similar Problems
分析:
老题目了!分析略。
方法1:
反复相除。时间复杂度o(lg(n))
方法2:
log函数取对数
方法3:
位运算,没有方法1快呢!
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/51212846
原作者博客:http://blog.csdn.net/ebowtang
本博客LeetCode题解索引:/article/3664871.html
Submissions: 14338 Difficulty: Easy
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?
Credits:
Special thanks to @yukuairoy for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Tags
Bit Manipulation
Show Similar Problems
分析:
老题目了!分析略。
方法1:
反复相除。时间复杂度o(lg(n))
class Solution { public: bool isPowerOfFour(int num) { while(num>0 && num%4==0) num/=4; return num==1; } };
方法2:
log函数取对数
class Solution { public: bool isPowerOfFour(int num) { double res = log10(num) / log10(4); //有精度问题,不要用以指数2.718为低的log函数 return (res - int(res) == 0) ? true : false; } };
方法3:
位运算,没有方法1快呢!
class Solution { public: bool isPowerOfFour(int num) { if (num <= 0) return false; //(num & (num-1)) == 0这个条件有可能是2的幂产生的。 //(num & 0x55555555) != 0这个条件为的是铲除2的幂 if ( (num & (num-1)) == 0 && (num & 0x55555555) != 0 ) return true; return false; } };
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/51212846
原作者博客:http://blog.csdn.net/ebowtang
本博客LeetCode题解索引:/article/3664871.html
相关文章推荐
- 地理定位 (iOS 9.0)
- LeetCode_OJ【72】Edit Distance
- 线性时间内统计一个字符串中每个字符出现的次数
- CSS3 动画
- CodeForces - 552C Vanya and Scales (进制转换&技巧)好题
- ppt制作干货
- vector 介绍
- 测试作业1
- Json和XML解析
- 解题报告:HDU4704Sum 费马小定理+快速幂
- 巴什博奕(Bash Game)
- websocket
- MySQL中group by max如何提取最大的一条记录
- java 读取properties + 类反射的应用
- JSP ffmpeg实现视频截图
- 为什么最近要弄CANopen以及资料来源
- 手把手教你使用Git(简单,实用)
- Array.asList()注意
- C#—异常应用(正则表达式)
- Java 重写(Override)与重载(Overload)