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 231 Power of TwoLeetCode
- LeetCode | 1 Two SumLeetCode
- Leetcode 1 two sumLeetCode
- LeetCode | 349 Intersection Of Two ArraysLeetCode
- LeetCode-1 Two SumLeetCode
- python: leetcode - 1 Two SumPythonLeetCode
- Leetcode 29 Divide Two IntegersLeetCodeIDE
- [LeetCode]1.Two SumLeetCode
- LeetCode 2 Add Two NumbersLeetCode
- 【Leetcode】1029. Two City SchedulingLeetCode
- leetcode-29. Divide Two IntegersLeetCodeIDE
- LeetCode-2 Add Two NumbersLeetCode
- Leetcode 21 Merge Two Sorted ListsLeetCode
- LeetCode: Two sum(兩數之和)LeetCode
- [LeetCode] 29. Divide Two IntegersLeetCodeIDE
- Leetcode 4 Median of Two Sorted ArraysLeetCode
- LeetCode 2. Add Two NumbersLeetCode
- leetcode 371. Sum of Two IntegersLeetCode
- LeetCode Two Sum(001)解法總結LeetCode
- leetcode 350. Intersection of Two Arrays IILeetCode
- 【LeetCode】617. Merge Two Binary TreesLeetCode
- Leetcode 160. Intersection of Two Linked ListsLeetCode
- LeetCode T29 Divide Two IntegersLeetCodeIDE
- LeetCode 21. Merge Two Sorted ListsLeetCode
- LeetCode 4. Median of Two Sorted ArraysLeetCode
- LeetCode #1:Two Sum(簡單題)LeetCode
- LeetCode 617. Merge Two Binary TreesLeetCode
- [LeetCode] 3090. Maximum Length Substring With Two OccurrencesLeetCode
- [LeetCode] 884. Uncommon Words from Two SentencesLeetCode
- LeetCode 1305 All Elements in Two Binary Search TreesLeetCode
- python leetcode 之兩數之和(two sum)PythonLeetCode
- [LeetCode] 1385. Find the Distance Value Between Two ArraysLeetCode
- LeetCode Median of Two Sorted Arrays(004)解法總結LeetCode
- [leetcode] 1624. Largest Substring Between Two Equal CharactersLeetCode
- LeetCode Merge Two Sorted Lists(021)解法總結LeetCode
- LeetCode2: Add two numbers(兩數相加)LeetCode
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode
- [LeetCode] 3226. Number of Bit Changes to Make Two Integers EqualLeetCode