[LeetCode] Power of Two

Power of Two

Given an integer, write a function to determine if it is a power of two.

Credits:Special thanks to@jianchao.li.fighterfor adding this problem and creating all test cases.

解题思路:

这道题的题意是判断一个数是不是2的幂。有几个问题需要确定一下:

1、1也是2的幂,是0次幂

2、将一个整数向左移一位,相当于这个整数乘以2,向右移一位,相当于该整数除以2

3、注意大整数的溢出情况。

下面是代码:

class Solution {public:bool isPowerOfTwo(int n) {long long num = 1;while(num <= n){if(num==n){ //先判断,考虑到1的情况return true;}num = num << 1;}return false;}};

版权声明:本文为博主原创文章,,未经博主允许不得转载。

人言未必皆真,听言只听三分。

[LeetCode] Power of Two

相关文章:

你感兴趣的文章:

标签云: