zoukankan      html  css  js  c++  java
  • LeetCode 231. 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. 利用Java自带函数 
    public class Solution {
        public boolean isPowerOfTwo(int n) {
            return n == 0 ? false : n == Math.pow(2, Math.round(Math.log(n) / Math.log(2)));
        }
    }

    Math.pow() 进行指数运算;

    Math.log() 进行底数为e的对数运算;

    Math.round() 进行四舍五入运算;

    n == Math.pow(2, Math.round(Math.log(n) / Math.log(2))) 这一句很巧妙地判断了n是否是2的某次方数。

    2. 位运算

    2的次方可以用1向左移位得到

    public class Solution {
        public boolean isPowerOfTwo(int n) {
            if (n < 1) return false;
            
            int m = 1;
            for (int i = 1; i < 32 && m <= n; i++) {
                if(m == n) return true;
                m <<= 1;
            }
            
            return false;
        }
    }

    3. Power of 2 means only one bit of n is '1', so use the trick n&(n-1)==0 to judge whether that is the case

    2的某次方只有一位1,该数减一与该数位与的话结果为0的话肯定是2的某次方。

    public class Solution {
        public boolean isPowerOfTwo(int n) {
            if (n < 1) return false;
            return (n & (n-1)) == 0;
        }
    }
  • 相关阅读:
    python-高阶函数(map,reduce,filter)
    python-函数(补充)
    python-局部变量与全局变量
    python-函数
    字符串格式化
    pycharm2019.1激活方法(亲测可用)
    python-集合
    python-字典
    keepalivd 配置
    zabbix3 agent端安装
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5364447.html
Copyright © 2011-2022 走看看