Leetcode-Power of 2,3,4
来源:互联网 发布:手机淘宝7.1.1版本 编辑:程序博客网 时间:2024/04/28 07:00
问题描述
Given an integer, write a function to determine if it is a power of x.
在这里,我们考虑x=2,3,4三种情况
Follow up:
Could you do it without using any loop / recursion?
一般解法
以x==3为例
bool isPowerOfThree(int n) { while (n >= 1) { if (n == 1 || n == 3) return true; else { if (n % 3) break; n /= 3; } } return false; }
特殊解法
x==2
bool isPowerOfTwo(int n) { return n>0 && (n&(n-1))==0;}
x==4
基于x为2,考虑4的整数次幂的二进制中1都在特殊的位置,因此我们使用”num & 0x55555555==num”来检验是否位置正确。
bool isPowerOfFour(int num) { return num>0 && (num&(num-1))==0 && (0x55555555&num)==num;}
x==3
在这里借助log换底公式求其对应整数次,然后由于直接(log(n)/log(3))在测试243时会报错,所以添加了round()。
bool isPowerOfThree(int n) { return n>0 && (n==pow(3,round(log(n)/log(3)))); }
0 0
- Leetcode-Power of 2,3,4
- Leetcode 231 and 342. Power of 2, Power of 4
- LeetCode 342 power of 4
- [LeetCode] Power of Two
- 【LeetCode】Power of Two
- [Leetcode]Power of Two
- [leetCode] Power of Two
- leetcode --Power of Two
- leetcode: Power of Two
- LeetCode Power of Two
- [LeetCode] Power of Two
- LeetCode Power of Two
- [leetcode] Power of Two
- [Leetcode]Power of Two
- Leetcode: Power of Two
- [LeetCode]Power of Two
- leetcode | Power of Two
- 【leetcode】Power of Two
- leetcode 63.Unique Paths II
- php基础-相对路径与绝对路径
- JAVA exception异常处理+I/O操作读写文件 笔记
- 用STL进行字符串的分割
- window ant安装与配置
- Leetcode-Power of 2,3,4
- 快速幂取模
- 10个关于JavaScript小技巧
- 1003 我要通过!(20)
- 服务器U盘安装安装centos
- 获取联系人信息
- 素数的筛法,n*long(n)和O(n)的写法
- <LeetCode OJ> 105. Construct Binary Tree from Preorder and Inorder Traversal
- 汇编学习(十三)8086汇编拾遗 (12)