• Power of Two


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

    Analyse: ***Notice that if a number is a power of 2, then the highest binary digit is 1 and the remaining digits are all 0s. So n & (n-1) = 0. If a number is not a power of 2, then n & (n - 1) != 0.

    Runtime: 4ms.

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

     

    Other solution:

    1. Runtime: 8ms.

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

    2. Rutime: 8ms

     1 class Solution {
     2 public:
     3     bool isPowerOfTwo(int n) {
     4         if(n <= 0 ) return false;
     5         
     6         long long num = 1;
     7         while(num <= n){
     8             if(num == n) return true;
     9             num <<= 1;
    10         }
    11         return false;
    12     }
    13 };
  • 相关阅读:
    团队选题与评审
    消息管家
    团队展示
    功能规格说明书
    测试与优化
    git分支管理
    MVC小结
    .Net基础加强
    结对编程
    个人作业1_软件工程
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4768306.html
Copyright © 2020-2023  润新知