## 一. 题目描述
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