zoukankan      html  css  js  c++  java
  • [LeetCode]Power of Two

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

    [思路]

    1)考虑各种边界情况。

    输入是整型值,说明不用考虑2的负指数情况。

    2)假设一个数是二的倍数。说明他的二进制形式仅仅有一位是1。做好推断就可以。

    循环推断1的位数解法最easy想到。

    Leetcode上有种解法,就是让n&n-1,假设n仅仅含有一个1那么结果就是零。

    简单解法:

    class Solution {
    public:
        bool isPowerOfTwo(int n) {
           if(n<=0) return false;
           int count = 0;
           while(n!=0){
               if(n%2!=0){
                   count++;
               }
               n = n>>1;
               if(count>1)
                return false;
           }
            return true;
        }
    
    };
    奇妙解法:

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


  • 相关阅读:
    go第二天
    go第一天
    engish
    english
    git 生成公钥
    tp5 验证码
    css处理文本折行截断
    数组对象总结(牢记)
    全局css样式
    Flexbox 弹性盒子布局
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/8468828.html
Copyright © 2011-2022 走看看