Leetcode 231. Power of Two
方法1: 最簡單想到的logn演算法。把n不停的除以2,最後得到1就是true,不是1就是false。時間複雜logn,空間1.
class Solution {
public boolean isPowerOfTwo(int n) {
long N = n;
return helper(N);
}
private boolean helper(long n){
if(n < 0) return false;
if(n == 0) return false;
if(n == 2 || n == 1) return true;
if(n % 2 != 0){
return false;
}else{
return helper(n / 2);
}
}
}
方法2: 利用二進位制表示n,然後如果是power of 2,然後(n的二進位制) & (-n的二進位制)應該為n。時間複雜1.空間複雜1.
class Solution {
public boolean isPowerOfTwo(int n) {
if (n == 0) return false;
long x = (long) n;
return (x & (-x)) == x;
}
}
總結:
- 無
相關文章
- Leetcode Power of TwoLeetCode
- Leetcode 231 Power of TwoLeetCode
- LeetCode 第 231 題 (Power of Two)LeetCode
- 【LeetCode 231_整數_位運算】Power of TwoLeetCode
- Leetcode Two SumLeetCode
- [LeetCode-231] Power of Two(判斷一個數是不是2的若干次冪)LeetCode
- Leetcode 1 two sumLeetCode
- Leetcode-Two SumLeetCode
- Two Sum leetcode javaLeetCodeJava
- LeetCode | 1 Two SumLeetCode
- [LeetCode]1.Two SumLeetCode
- LeetCode----1. Two SumLeetCode
- LeetCode 1.Two NumsLeetCode
- LeetCode1:Two SumLeetCode
- Leetcode Divide Two IntegersLeetCodeIDE
- Leetcode Add Two NumbersLeetCode
- [LeetCode]1. Two SumLeetCode
- LeetCode OJ : 1 Two SumLeetCode
- LeetCode-1 Two SumLeetCode
- LeetCode | 349 Intersection Of Two ArraysLeetCode
- LeetCode 第 342 題(Power of Four)LeetCode
- Leetcode 326. Power of ThreeLeetCode
- LeetCode 2 Add Two NumbersLeetCode
- LeetCode: Two sum(兩數之和)LeetCode
- Leetcode 29 Divide Two IntegersLeetCodeIDE
- python: leetcode - 1 Two SumPythonLeetCode
- LeetCode Problem-Sum of Two IntegersLeetCode
- [leetCode][013] Two Sum 2LeetCode
- Leetcode Merge Two Sorted ListsLeetCode
- Leetcode Median of Two Sorted ArraysLeetCode
- Leetcode-Divide Two IntegersLeetCodeIDE
- [LeetCode] Two Sum 兩數之和LeetCode
- Leetcode-Add Two NumbersLeetCode
- Add Two Numbers leetcode javaLeetCodeJava
- Divide Two Integers leetcode javaIDELeetCodeJava
- LeetCode 第 326 題 (Power of Three)LeetCode
- leetcode-29. Divide Two IntegersLeetCodeIDE
- Leetcode 4 Median of Two Sorted ArraysLeetCode