[leetcode-342]Power of Four(java)
来源:互联网 发布:ubuntu终端快捷键 编辑:程序博客网 时间:2024/06/05 17:07
原题链接:https://leetcode.com/problems/power-of-four/
思路:首先判断是否是2的幂,如果是的话,再去判断是否为4的幂,判断2的幂要求整数的bit位中只有一个1,而这可以根据num & (num -1)来判断。
得到结果后,最佳的方案是能找到1后面有多少个0,然后这个个数对2取余,如果为0,表示可以整除。但是我没找到方法。
public class Solution { public boolean isPowerOfFour(int num) { if(num < 0) return false; int tmp = num-1; if((tmp & num) == 0){ while(num != 0 && num != 1){ num = num >> 2; } if(num == 1) return true; } return false; }}
2、在网上看到了一种做法:思想是如果一个数为4的倍数,那么这个数-1一定可以被3整除,可以用数学归纳法很容易得到证明。
public class Solution { public boolean isPowerOfFour(int num) { if(num < 0) return false; int tmp = num-1; return (num & tmp) == 0 && tmp % 3 == 0; }}
0 0
- [leetcode-342]Power of Four(java)
- (LeetCode 342) Power of Four
- 【LeetCode-342】Power of Four
- Power of Four leetcode 342
- Leetcode Power of Four 342
- 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
- [LeetCode]Power of Four
- Power of Four-Leetcode
- LeetCode Power of Four
- LeetCode - Power of Four
- 支持各种屏幕尺寸
- 如何在MathType中设置字体默认颜色
- C-结构体之位域(位段)
- linux中用户及用户组
- 支持各种屏幕密度
- [leetcode-342]Power of Four(java)
- 模版方法( Template Method) Java
- 字符编码笔记:ASCII,Unicode和UTF-8
- Android第三方开源下拉框:NiceSpinner
- *leetcode #76 in cpp
- Fragment用handler向Activity发送消息并调用Activity的Handler.Callback
- linux命令小结
- UI更新三种方法
- ios开发:使用NSThread实现多线程