【Leetcode】231. Power of Two(判断是否为2的次方幂)

左手的ㄟ右手 2022-01-23 08:59 335阅读 0赞

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

Example 1:

  1. Input: 1
  2. Output: true
  3. Explanation: 20 = 1

Example 2:

  1. Input: 16
  2. Output: true
  3. Explanation: 24 = 16

Example 3:

  1. Input: 218
  2. Output: false

题目大意:

给出一个数判断其是否为2的次方幂。

解题思路:

我们发现2的次方幂都具有以下特征:

2-10 4-100 8-1000 …..

所以我们发现当这个数与比其小一的数进行&运算时会产生0,如果不是则不会产生0。

  1. class Solution {
  2. public:
  3. bool isPowerOfTwo(int n) {
  4. if(n<1) return false;
  5. return n & (n-1) ?false:true;
  6. }
  7. };

发表评论

表情:
评论列表 (有 0 条评论,335人围观)

还没有评论,来说两句吧...

相关阅读