[LeetCode] 342. Power of Four
来源:互联网 发布:淘宝api 获取卖家订单 编辑:程序博客网 时间:2024/05/16 23:51
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?
class Solution {public: bool isPowerOfFour(int num) { return (num > 0) && (num & (num - 1)) && (num & 0x55555555 == num); }};
首先,易知,如果一个数是4的幂次方,那么这个数必然是2的偶数次幂。
分解开来,就是要满足两点
1. 必须是2的幂次方
2. 必须是偶数次幂
从二进制的角度来看,就是要仅有一个bit位置1,且这个bit位必须是偶数偏移。
对于第一点要求而言,n & (n - 1) == 0即可。具体分析参见另一篇blog。
对于第二点要求而言,与上(01010101010101010101010101010101)这样一个bitmask即可,其只在偶数偏移的位置上置位。
阅读全文
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
- SAP product set type
- mysql使用union顺序混乱
- BZOJ 4034 :[HAOI2015]树上操作 树链剖分裸题
- 区间选点问题
- javascript字符串方法汇总
- [LeetCode] 342. Power of Four
- Linux shell ${}简单用法
- 不容错过,最全的安卓架构合集-(从零开始搭建android框架系列(2))
- 谈谈对Spring IOC的理解
- 小米笔记本2 Ubuntu 16.04下安装Tensorflow GPU 1.2.1版本说明
- Tomcat -- 多个Context启动冲突的问题解决
- PAT甲级真题及训练集(19)--1020. Tree Traversals (25)(后序,中序建树,很重要)
- GsyVideoPlayer视频分析(二)------------列表视频播放视频
- 【dlib】人脸68特征点检测