231. Power of Two

Love The Way You Lie 2023-07-03 02:36 120阅读 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,直到为0。循环中模2,如果结果不等于0,表示不是2的次幂。

  1. class Solution {
  2. public:
  3. bool isPowerOfTwo(int n) {
  4. if(n<=0)
  5. return false;
  6. while(n>1)
  7. {
  8. if(n%2 != 0)
  9. {
  10. return false;
  11. }
  12. n = n/2;
  13. }
  14. return true;
  15. }
  16. };

方法二:整数n 与n-1 模运算(本质上是去掉最低位的1),如果结果不等于0,表示不是2的次幂。

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

发表评论

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

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

相关阅读