[LeetCode] Power of Three | Power of Two

简介: Given an integer, write a function to determine if it is a power of three.Follow up: Could you do it without using any loop / recursion?解题思路log运算。实现代码//Runtime: 18 mspublic cl

Given an integer, write a function to determine if it is a power of three.

Follow up:
Could you do it without using any loop / recursion?

解题思路

log运算。

实现代码

//Runtime: 18 ms
public class Solution {
    public boolean isPowerOfThree(int n) {
        double res = Math.log(n) / Math.log(3);
        return Math.abs(res - Math.round(res)) < 1e-10;
    }
}

Given an integer, write a function to determine if it is a power of two.

解题思路

2的n次方,必然大于0;而且二进制位中只有一个1。

实现代码

public class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && (n & n - 1) == 0;
    }
}
目录
相关文章
LeetCode 342. Power of Four
给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。
56 0
LeetCode 342. Power of Four
|
Java C++
LeetCode之Power of Two
LeetCode之Power of Two
91 0
|
Java
[LeetCode]--326. Power of Three
Given an integer, write a function to determine if it is a power of three. Follow up: Could you do it without using any loop / recursion? Credits: Special thanks to @dietpepsi for addin
1095 0
|
Java
[LeetCode]--342. Power of Four
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
1139 0
[LeetCode]--231. Power of Two
Given an integer, write a function to determine if it is a power of two. Credits: Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 如果是power of
1073 0
[LeetCode] Power of Four
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
1450 0