342. Power of Four
来源:互联网 发布:吾生也有涯而知也启示 编辑:程序博客网 时间:2024/06/05 22:54
题目:
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?
思路:本题与power of two,power of three略有不同,不能简单的套用power of three的方法。可以分析2、4的幂都有哪些特征,可以从2进制角度考虑,
1:1
4:100
8:1000
16:10000
32:100000
64:1000000
总结规律发现满足2或4的幂必须num&(num-1) == 0,其次每4位用0101判断是否为4的幂
代码:
class Solution {public: bool isPowerOfFour(int num) { return num > 0 && (num&(num-1)) == 0 && (num & 0x55555555) != 0; //0x55555555 is to get rid of those power of 2 but not power of 4 //so that the single 1 bit always appears at the odd position }};
阅读全文
0 0
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four
- 342. Power of Four*
- 342. Power of Four
- 342. Power of Four
- Android-JS&Native交互的几种可行性方案&H5白屏问题解决方式
- Educational Codeforces Round 26 E. Vasya's Function(数论)
- spring配置datasource三种方式
- 抽象类
- ajax 请求二进制流 图片 文件 XMLHttpRequest 请求并处理二进制流数据 之最佳实践
- 342. Power of Four
- OS-计算机体系结构和内存层次
- mapreduce解决数据倾斜的思路
- 每股收益具体怎么来的
- Oracle10g监听夯的处理方式
- frameset
- 一、人的价值体系
- Spring-不同配置方式的比较
- HDU 1720