342. Power of Four
来源:互联网 发布:ubuntu配置网络 编辑:程序博客网 时间:2024/05/14 23:58
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 2 和power of 3 通用的做法,可以写成递归的, 这个是适用于任何power of n的解法。
class Solution {public: bool isPowerOfFour(int num) { if(num <= 0) { return false; } if(num == 1) { return true; } return num%4 == 0 && isPowerOfFour(num/4); }};
但是显然power of 4是有其自己的特征的:
1)num <= 0的肯定不是
2)power of 2 的数包含power of 4的,power of 4的数也满足 num&(num-1) == 0
3) 但是要能除掉power of 2中32,8之类的数
64 32 16 8 4 2 1
1 0 0 0 0 0 0 是power of 4
1 0 0 0 0 0 不是
1 0 0 0 0 是
1 0 0 0 不是
所以可以&(1 0 1 0 1 0 1)的话,power of 4的数不为0,但power of 2的数为0
class Solution {public: bool isPowerOfFour(int num) { return num > 0 && (num &(num-1)) == 0 && (num & 0x55555555) != 0; }};
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
- 数论快速入门(同余、扩展欧几里德、中国剩余定理、大素数测定和整数分解、素数三种筛法、欧拉函数以及各种模板)
- Install Shield教程
- scrapy简单爬取内容
- HDU-1850-Being a Good Boy in Spring Festival【Nim博弈】
- Linux内核---43.文件系统的挂载
- 342. Power of Four
- 动态规划dp(简单应用)hdu 2151 Worm(石头)
- BZOJ2850 巧克力王国
- ASP.NET Process Model之一:IIS 和 ASP.NET ISAPI
- 响应式布局一
- iOS开发 刮刮乐效果的实现
- c 语言中宏定义和定义全局变量的区别
- Linux内核---44.关于中断号与中断引脚
- First Bad Version