LeetCode 342. Power of Four
来源:互联网 发布:电视直播点播软件 编辑:程序博客网 时间:2024/05/17 06:21
描述
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?
分析
判断一个数是不是4的次方。
我们知道num & (num - 1)可以用来判断一个数是否为2的次方数,更进一步说,就是二进制表示下,只有最高位是1,那么由于是2的次方数,不一定是4的次方数,比如8,所以我们还要其他的限定条件,我们仔细观察可以发现,4的次方数的最高位的1都是计数位,那么我们只需与上一个数(0x55555555) <==> 1010101010101010101010101010101,将 2 的 N 次方中那些不是 4 的 N 次方的数去掉。
代码
class Solution {public: bool isPowerOfFour(int num) { return num > 0 && (num & (num - 1)) == 0 && (num & 0x55555555); }};
0 0
- LeetCode *** 342. Power of Four
- LeetCode -- 342. Power of Four
- LeetCode-342. Power of Four
- LeetCode 342. Power of Four
- [leetcode] 342. Power of Four
- leetcode-342. Power of Four
- LeetCode.342. Power of Four
- LeetCode 342. Power of Four
- leetcode 342. Power of Four
- 342.[leetcode]Power of four
- leetcode 342. Power of Four
- LeetCode-342.Power of Four
- 【leetcode】342. Power of Four
- LeetCode 342. Power of Four
- LeetCode 342. Power of Four
- [Leetcode]342. Power of Four
- LeetCode 342. Power of Four
- [leetcode] 342. Power of Four
- python之函数cmp
- Elasticsearch V5.1.1安装IK分词
- kruskal算法
- <HTML> 给input文本框中添加灰色提示字
- 12 duplicate symbols for architecture armv7
- LeetCode 342. Power of Four
- Direct3D的四大变换
- strangeioc test learn
- 学习学习
- for 续4
- C语言逗号运算符和逗号表达式
- Ajax请求Json遇到的问题总结
- 模块继续
- Ubuntu mysql 安装