LeetCode 342. Power of Four
2016-05-20 19:19
459 查看
https://leetcode.com/problems/power-of-four/
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?
数学题+位运算。
因为是signed 32 bits,所以先保证num > 0。
然后2的幂的特征(num & (num - 1)) == 0,e.g. 0x1000 & 0x0111。
再对2的幂中筛选不是4的幂的。4的幂的二进制中1总是出现在奇数位,e.g. 4^1(0x0100), 4^2(0x00010000), 4^3(0x01000000),其他则是在偶数位,e.g. 2^1(0x0010), 2^3(0x1000), 2^5(0x00100000)。所以(num & 0x55555555) != 0,这里0x55555555正是signed 32 bits integer。
之前没注意位运算运算符&优先级低于==,需要加上括号。
C语言运算符_百度百科
http://baike.baidu.com/link?url=7D3QzeLlfI9pELy4OqJyyGE-WwRZhZ_mCI8ZSI6YdQHrldIIly3WnCTGnjzbypatAAodGjGFTUrTGJxkIbWFBq#2
还有一种解法(4^n - 1)都可以被3整除,所以可以判断(num > 0) && ((num & (num - 1)) == 0) && ((num - 1) % 3 == 0)
https://helloacm.com/how-to-check-if-integer-is-power-of-four-cc/
View Code
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?
数学题+位运算。
因为是signed 32 bits,所以先保证num > 0。
然后2的幂的特征(num & (num - 1)) == 0,e.g. 0x1000 & 0x0111。
再对2的幂中筛选不是4的幂的。4的幂的二进制中1总是出现在奇数位,e.g. 4^1(0x0100), 4^2(0x00010000), 4^3(0x01000000),其他则是在偶数位,e.g. 2^1(0x0010), 2^3(0x1000), 2^5(0x00100000)。所以(num & 0x55555555) != 0,这里0x55555555正是signed 32 bits integer。
之前没注意位运算运算符&优先级低于==,需要加上括号。
C语言运算符_百度百科
http://baike.baidu.com/link?url=7D3QzeLlfI9pELy4OqJyyGE-WwRZhZ_mCI8ZSI6YdQHrldIIly3WnCTGnjzbypatAAodGjGFTUrTGJxkIbWFBq#2
还有一种解法(4^n - 1)都可以被3整除,所以可以判断(num > 0) && ((num & (num - 1)) == 0) && ((num - 1) % 3 == 0)
https://helloacm.com/how-to-check-if-integer-is-power-of-four-cc/
#include <iostream> using namespace std; class Solution { public: bool isPowerOfFour(int num) { return ((num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) != 0)); } }; int main () { Solution testSolution; bool result; result = testSolution.isPowerOfFour(16); cout << result << endl; char ch; cin >> ch; return 0; }
View Code
相关文章推荐
- 对关系型数据库规范化理论理解的图解
- C++程序错误集锦,如:thiscall,_tmain已经定义,重载,未定义的标识符
- flume介绍及扩展开发心得
- Ioc(Inversion of Control)
- iOS多线程开发--NSThread NSOperation GCD
- 开闭、里氏代换、依赖倒转、单一职责、迪米特五种原则
- [微信开发] 微信网页授权Java实现
- Java学习笔记(六)
- 上传图片
- Java/Android 代码规范
- java设计模式学习-工厂模式
- apktool使用
- 树链剖分
- Python 进阶 —— 迭代器与生成器
- 【原】iOS学习之Swift之语法1(精简版)
- 如何把Android手机变成一个WIFI下载热点? — 报文转发及DNS报文拦截
- jQuery中登录友好提示系列(1)
- 页面自动的分页 跳转
- lua 小数点后面几位
- mongodb