Leetcode 231 Power of Two
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1 Output: true Explanation: 20 = 1
Example 2:
Input: 16 Output: true Explanation: 24 = 16
Example 3:
Input: 218 Output: false
這個題目考察的為位運算,題目要求寫一個函式來判斷是不是二的冪,主要有兩種方法:
1)
/*
將整數和其相反數相與,效果即為只留下最左邊的一,如果為二的冪則字串中只有一個1,如果不是的話就有多個1
*/
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & -n) == n;
}
}
2)
/*
這個方法為將最大的數相餘n,如果n為二的冪的話,那麼相餘之後必定為0,即可以判斷
/*
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && (1 << 30) % n == 0;
}
};
相關文章
- Leetcode 231. Power of TwoLeetCode
- leetcode 231 2的冪LeetCode
- Leetcode 1 two sumLeetCode
- LeetCode | 1 Two SumLeetCode
- Leetcode 29 Divide Two IntegersLeetCodeIDE
- LeetCode 2 Add Two NumbersLeetCode
- LeetCode-1 Two SumLeetCode
- [LeetCode]1.Two SumLeetCode
- LeetCode | 349 Intersection Of Two ArraysLeetCode
- python: leetcode - 1 Two SumPythonLeetCode
- 【CS231n】Spring 2020 Assignments - Assignment1 - Two Layer NetSpring
- leetcode231 2的冪(JAVA版)LeetCodeJava
- 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】1029. Two City SchedulingLeetCode
- leetcode 371. Sum of Two IntegersLeetCode
- LeetCode 21. Merge Two Sorted ListsLeetCode
- LeetCode 4. Median of Two Sorted ArraysLeetCode
- LeetCode #1:Two Sum(簡單題)LeetCode
- 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 617. Merge Two Binary TreesLeetCode
- LeetCode T29 Divide Two IntegersLeetCodeIDE
- python leetcode 之兩數之和(two sum)PythonLeetCode
- [LeetCode] 884. Uncommon Words from Two SentencesLeetCode
- [LeetCode] 3090. Maximum Length Substring With Two OccurrencesLeetCode
- LeetCode 1305 All Elements in Two Binary Search TreesLeetCode
- LeetCode2: Add two numbers(兩數相加)LeetCode
- LeetCode Median of Two Sorted Arrays(004)解法總結LeetCode
- [leetcode] 1624. Largest Substring Between Two Equal CharactersLeetCode
- LeetCode Merge Two Sorted Lists(021)解法總結LeetCode