【LeetCode】Power of Four 解题报告
来源:互联网 发布:软件打不开 编辑:程序博客网 时间:2024/05/16 18:53
Power of Four
[LeetCode]
https://leetcode.com/problems/power-of-four/
Total Accepted: 9305 Total Submissions: 28083 Difficulty: Easy
Question
Given an integer, write a function to determine if it is a power of 4.
Ways
和刚才那个是否为2的倍数好像。嗯。
方法一
我想的方法。很笨。
首先判断是否为2的倍数。n&(n-1)
然后在把8这些数给去掉。我想的是如果一个数为4的幂的话,那么它二进制中1后面一定有偶数个0。
所以这么写的:
public class Solution { public boolean isPowerOfFour(int num) { if(num<=0) return false; if(num==1) return true; if((num & (num-1))==0){ while(num>0){ num>>>=2; if(num==1){ return true; } } } return false; }}
AC:2ms
效率凑活。
查了一下,发现还有更好的方法。就是判断二进制中1出现的位数是不是在奇数位。用0101 0101 ……来进行排除。16进制数为:0x55555555。
public class Solution { public boolean isPowerOfFour(int num) { return num > 0 && (num & (num - 1)) ==0 && (num & 0x55555555) !=0; }}
最起码代码比我的精简。嗯。
Date
2016/5/1 17:36:06
0 0
- [leetcode] 342. Power of Four 解题报告
- 【LeetCode】Power of Four 解题报告
- leetcode 342. Power of Four 解题报告
- leetcode解题报告-342. Power of Four
- [Leetcode] 342. Power of Four 解题报告
- [LeetCode]Power of Four
- Power of Four-Leetcode
- LeetCode Power of Four
- LeetCode - Power of Four
- LeetCode:Power of Four
- leetcode---Power of Four
- [LeetCode] Power of Four
- 【Leetcode】Power of Four
- [Leetcode]Power of Four
- LeetCode: Power of Four
- LeetCode Power of Four
- [Leetcode] Power of Four
- LEETCODE-- Power of Four
- 网络设备互联技术· 『1』
- javaScript学习笔记——如何让<canvas>动起来
- java实用工具之XOM
- 剑指offer(65):获取数据流中的中位数
- WebSphere8.5的安装
- 【LeetCode】Power of Four 解题报告
- 网络七层协议
- phpMyAdmin配置与安装
- Sping 自己学习心得(IOC)
- Java实现服务器端动态流断点续传下载支持
- Java千百问_06数据结构(004)_java数据类型的字面值是什么
- A Tour of Golang (二)
- IMF传奇行动第85课:Spark Streaming第四课:基于HDFS的Spark Streaming案例实战和内幕源码解密
- eclipse luna4.4配置beans.xml和hibernate.cfg.xml提示类的包路径信息