LeetCode 231. Power of Two
https://leetcode.com/problems/power-of-two/description/
Given an integer, write a function to determine if it is a power of two.
- 简单数学题,位运算
- 2的幂在2进制中只有1个0,所以可以利用n & (n -1) == 0来判断是不是2的幂
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // 2 // main.cpp 3 // LeetCode 4 // 5 // Created by Hao on 2017/3/16. 6 // Copyright © 2017年 Hao. All rights reserved. 7 // 8 9 #include <iostream> 10 using namespace std; 11 12 class Solution 13 { 14 public: 15 bool isPowerOfTwo(int n) 16 { 17 return ((n > 0) && ((n & (n - 1)) == 0)); 18 } 19 }; 20 21 int main(int argc, char* argv[]) 22 { 23 Solution testSolution; 24 25 auto nums = {0, 1, 2, 3, 4, 8, 16, 1000, 1024}; 26 27 for (auto num : nums) 28 { 29 cout << num << " isPowerOfTwo ? " << testSolution.isPowerOfTwo(num) << endl; 30 } 31 32 return 0; 33 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
0 isPowerOfTwo ? 0 1 isPowerOfTwo ? 1 2 isPowerOfTwo ? 1 3 isPowerOfTwo ? 0 4 isPowerOfTwo ? 1 8 isPowerOfTwo ? 1 16 isPowerOfTwo ? 1 1000 isPowerOfTwo ? 0 1024 isPowerOfTwo ? 1 Program ended with exit code: 0