## 一. 題目描述
Given an integer, write a function to determine if it is a power of two.
## 二.題目分析
該題要求簡單,給定一個整數,判斷其是不是`2`的整數次冪,這道題的解題關鍵是找到一個規律:如果一個數字是`2`的整數次冪,若將該數寫為二進制數,這個二進制數中有且僅有一位為`1`,其余均為`0`。根據這一性質,不難給出以下給出兩種解決方法。
## 三.示例代碼
~~~
// 將n不停右移,比較二進制數中1出現的個數,count = 1時判定為ture
bool isPowerOfTwo(int n) {
int count = 0;
while (n > 0)
{
count+=(n&0x01);
n>>=1;
}
if(sum==1)
return true;
else
return false;
}
~~~
以下方法同樣利用了一個`2`的整數次冪的二進制寫法中有且僅有一位為1的性質。假設該數為n,根據這一性質,則`(n - 1)`必然是將n的最高位`1`置`0`,然后其余二進制位均置`1`,當且僅當這種情況下,有`(n&(n-1)) == 0`,一個例子:
n = 8 -> 1000?
n - 1 = 7 -> 0111?
則有:1000 & 0111 = 0000
~~~
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n>0) && (!(n&(n-1)));
}
};
~~~
- 前言
- 2Sum
- 3Sum
- 4Sum
- 3Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Search in Rotated Sorted Array
- Remove Element
- Merge Sorted Array
- Add Binary
- Valid Palindrome
- Permutation Sequence
- Single Number
- Single Number II
- Gray Code(2016騰訊軟件開發筆試題)
- Valid Sudoku
- Rotate Image
- Power of two
- Plus One
- Gas Station
- Set Matrix Zeroes
- Count and Say
- Climbing Stairs(斐波那契數列問題)
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle 2
- Integer to Roman
- Roman to Integer
- Valid Parentheses
- Reorder List
- Path Sum
- Simplify Path
- Trapping Rain Water
- Path Sum II
- Factorial Trailing Zeroes
- Sudoku Solver
- Isomorphic Strings
- String to Integer (atoi)
- Largest Rectangle in Histogram
- Binary Tree Preorder Traversal
- Evaluate Reverse Polish Notation(逆波蘭式的計算)
- Maximum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Longest Common Prefix
- Recover Binary Search Tree
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Binary Tree Zigzag Level Order Traversal
- Sum Root to Leaf Numbers
- Anagrams
- Unique Paths
- Unique Paths II
- Triangle
- Maximum Subarray(最大子串和問題)
- House Robber
- House Robber II
- Happy Number
- Interlaving String
- Minimum Path Sum
- Edit Distance
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Decode Ways
- N-Queens
- N-Queens II
- Restore IP Addresses
- Combination Sum
- Combination Sum II
- Combination Sum III
- Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Longest Consecutive Sequence
- Word Search
- Word Search II
- Word Ladder
- Spiral Matrix
- Jump Game
- Jump Game II
- Longest Substring Without Repeating Characters
- First Missing Positive
- Sort Colors
- Search for a Range
- First Bad Version
- Search Insert Position
- Wildcard Matching