LeetCode--No.342--Power of Four
来源:互联网 发布:python获取request参数 编辑:程序博客网 时间:2024/06/05 15:55
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?
方法一:
第一次写报错。因为忘记判断n的正负号。
public class Solution { public boolean isPowerOfFour(int num) { if(num <= 0) return false; while(num != 1){ if (num % 4 != 0) return false; num = num /4; } return true; }}
方法二:
首先判断n&(n-1) 是不是等于0.
如果等于0的话,证明n的二进制中,只含有一个1.也就是说,n是2的倍数。
再其次,判断n的二进制中,这个1的位置。是在奇数位还是偶数位。
0x55555555,实际上是0101,0101,0101,0101,0101,0101,0101,0101
二进制和十六进制是相通的。二进制的四位,相当于16进制的一位。
当n与0x55555555进行与运算之后,如果结果不为0,证明那个唯一的1,不在奇数位,则是正确的。否则,是错误的。
public class Solution { public boolean isPowerOfFour(int num) { if ((num & (num-1)) == 0) { if((num & 0x55555555) > 0) return true; } return false; }}
0 0
- LeetCode--No.342--Power of Four
- (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
- 经典算法面试题目-矩阵旋转90度(1.6)
- OSI七层模型的作用
- 最长公共子串
- 时间管理 | 要这样学习
- thinkphp 奇怪的问题
- LeetCode--No.342--Power of Four
- 经典算法面试题目-置矩阵行列元素为0(1.7)
- 进程
- 深入理解Dalvik字节码指令及Smali文件
- 创建进程
- [leetcode] 125. Valid Palindrome
- Android开发人员不得不收集的代码(持续更新中)
- 字符串反转
- LeetCode--No.27--Remove Element