Power of Two

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

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

 

2的次幂的特征就是,二进制表示中只有一位是1.

乘以2相当于左移一位,因此2^k的二进制相当于把1(2^0)向左移动k次

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n <= 0)
            return false;
        return (n & (n-1)) == 0;
    }
};

【LeetCode】231. Power of Two

相关文章:

  • 2022-12-23
  • 2021-11-24
  • 2022-12-23
  • 2021-05-02
  • 2021-06-23
  • 2021-10-16
  • 2022-02-01
  • 2021-09-19
猜你喜欢
  • 2021-05-22
  • 2022-03-05
  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案