273. Integer to English Words
2016-04-19 10:30
281 查看
Task:
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?
Some Questions:
Can I use the
log function?
Solution:
Obviously, we can use loop to check whether the given number is equal to 4,4^2,4^3,..,4^15.
But how to solve it without loops? In fact, we have solve the problem power of 2. It calculates whether the given number is a divisor of (1<<30).
So, this problem can we solve it by checking whether the given number is a divisor of (4^15)? Obviously, this is not enough, because 2 is also satisfies this condition. We
additionally have to ensure it is a even power of 2. How to check it? One way is to use log function. Let x=log(num)/log(2), if x is a even number than num is power of 4.
Another way is that let x=num|0x55555555, if x==0x55555555 than num is power of 4, because 5 is 0101 in binary system, it filters the number that the most significant digit in odd position.
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?
Some Questions:
Can I use the
log function?
Solution:
Obviously, we can use loop to check whether the given number is equal to 4,4^2,4^3,..,4^15.
But how to solve it without loops? In fact, we have solve the problem power of 2. It calculates whether the given number is a divisor of (1<<30).
So, this problem can we solve it by checking whether the given number is a divisor of (4^15)? Obviously, this is not enough, because 2 is also satisfies this condition. We
additionally have to ensure it is a even power of 2. How to check it? One way is to use log function. Let x=log(num)/log(2), if x is a even number than num is power of 4.
Another way is that let x=num|0x55555555, if x==0x55555555 than num is power of 4, because 5 is 0101 in binary system, it filters the number that the most significant digit in odd position.
Code:
class Solution { public: bool isPowerOfFour(int num) { if(num<=0)return false; int HAT=1<<30; if(HAT%num!=0)return false; return (num|0x55555555)==0x55555555; } };
class Solution { public: bool isPowerOfFour(int num) { if(num<=0)return false; int HAT=1<<30; if(HAT%num!=0)return false; double x=log(num*1.0)/log(2.0); int ix=x; return ix%2==0; } };
相关文章推荐
- 对我有价值的文章记录
- Java中的Constants类
- update_TypeError
- 英译中批量翻译
- linux 红帽6.5修改root密码
- ionic基础概念
- Mybatis学习记录(五)--整合spring开发Dao
- gdb
- java线程
- SQLite笔记
- 研发过程中动态看板的使用推广
- java 二进制 十进制 十六进制数据类型转换
- 第七篇——Mobile Apps,软件的曙光。
- mysql 删除重复数据保留一条
- Oracle数据库表的备份和数据表的删除操作
- 有字母a,b,c,输入值n为2.输出所有由3个字母组成的字符串.aa,ab,ac,ba,bb,bc,ca,cb,cc,如果n是3按这样规律输出
- 找第k大的数
- Linux Shell脚本之更新hosts文件以便于访问谷歌服务
- VCRuntime140.dll 丢失
- 如何做竞品评测