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;
        }
    }
  • 相关阅读:
    iOS
    UI基本视图控制
    堆和栈的区别 ?
    单例模式
    Object-c的类可以多重继承么?可以实现多个接口么?Category是什么?重写一个类的方式用继承好还是分类好?为什么?
    id
    协议
    分类(类别)
    #import和#include以及@class三者的区别?
    内存管理
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5364447.html
Copyright © 2011-2022 走看看