Leetcode 231. Power of Two

来源:互联网 发布:stm32单片机项目大全 编辑:程序博客网 时间:2024/06/01 03:58

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


方法一:

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if(n<1)return false;
        if(Integer.bitCount(n) == 1)return true;
        return false;
    }
}


方法二:

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if(n<1)return false;
        //return (int)Math.pow(2,Math.round(Math.log(n)/Math.log(2)))==n;
        return (Math.pow(2,(int)(Math.log(Integer.MAX_VALUE)/Math.log(2)))%n == 0);

//此处强制转换为int型应该放在pow的第二个参数处,这样 才符合2的整数次幂,如果放在pow函数外面,则可能是将一个浮点型的数字转换为了int型
    }
}


方法三:

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if(n<1)return false;
        return Math.pow(2,((int)Math.round(Math.log(n)/Math.log(2))))==n;
    }
}//此处int强制转换理由同上

0 0
原创粉丝点击