Leetcode题解 342. Power of Four
来源:互联网 发布:老布的淘宝店 编辑:程序博客网 时间:2024/05/17 08:17
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?
这道题让我们判断一个数是否为4的次方数,那么最直接的方法就是不停的除以4,看最终结果是否为1,参见代码如下:
解法一:
class Solution {public: bool isPowerOfFour(int num) { while (num && (num % 4 == 0)) { num /= 4; } return num == 1; }};
还有一种方法是跟Power of Three中的解法三一样,使用换底公式来做,讲解请参见之前那篇博客:
解法二:
public class Solution { public boolean isPowerOfFour(int num) { if(num<=0) return false; return (Math.log10(num)/Math.log10(4)-(int)(Math.log10(num)/Math.log10(4)))==0; }}
下面这种方法是网上比较流行的一种解法,思路很巧妙,首先根据Power of Two中的解法二,我们知道num & (num - 1)可以用来判断一个数是否为2的次方数,更进一步说,就是二进制表示下,只有最高位是1,那么由于是2的次方数,不一定是4的次方数,比如8,所以我们还要其他的限定条件,我们仔细观察可以发现,4的次方数的最高位的1都是计数位,那么我们只需与上一个数(0x55555555) <==> 1010101010101010101010101010101,如果得到的数还是其本身,则可以肯定其为4的次方数:
解法三:
public class Solution { public boolean isPowerOfFour(int num) { if(num<=0) return false; return (num&(num-1))==0&&(num&0x55555555)==num; }}
或者我们在确定其是2的次方数了之后,发现只要是4的次方数,减1之后可以被3整除,所以可以写出代码如下:
解法四:
class Solution {public: bool isPowerOfFour(int num) { return num > 0 && !(num & (num - 1)) && (num - 1) % 3 == 0; }};
0 0
- 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 342. Power of Four
- leetcode 342. Power of Four
- 342.[leetcode]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
- 带虚框的拖拽
- 《C编程专家》:程序员面试(附2)
- javascript数据相关内容
- iOS面试题整理(下) 仔细研读受益匪浅
- Leetcode Valid Anagram高效解法
- Leetcode题解 342. Power of Four
- SQLite数据库(一) 数据库概念 语法
- ssh证书登录(实例详解)
- VS2008+ Win10 之 WinCE SDK 编译错误(1) c1xx : fatal error C1023 & (2)fatal error C1001
- 进程间通信方式
- SDUT 2125 数据结构实验之串二:字符串匹配
- 第5.2节 函数getint接受自由格式的输入,并执行转换,将输入的字符分解成整数,且每次调用得到一个整数
- 《Mongodb》
- Kth Smallest Element in a BST