zoukankan      html  css  js  c++  java
  • 判断数幂

    2018-01-14 19:20:27

    • Power of Three

    问题描述:判断一个数是否为3的幂次,不允许使用循环或者递归。

    方法一、使用3的最大幂次来判断

    public boolean isPowerOfThree(int n) {
        // 1162261467 is 3^19,  3^20 is bigger than int
        // 如果不知道3的最大幂次,则可以通过以下方式进行计算
        // int maxPowerOfThree = (int)Math.pow(3, (int)(Math.log(0x7fffffff) / Math.log(3)));
        return n > 0 && (1162261467 % n == 0);
    }
    

     方法二、取对数来判断

    public boolean isPowerOfThree(int n) {
        return (Math.log10(n) / Math.log10(3)) % 1 == 0;
    }
    

    需要注意的是,不能使用自然对数为底,因为在自然对数里,会在243数字上出点小差错。

    log(243) = 5.493061443340548    log(3) = 1.0986122886681098
       ==> log(243)/log(3) = 4.999999999999999
    
    log10(243) = 2.385606273598312    log10(3) = 0.47712125471966244
       ==> log10(243)/log10(3) = 5.0

    发生这种情况是因为log(3)由于四舍五入实际上比它的真实值稍大,这使比率变小。

    方法三、使用转换进制来判断

    public boolean isPowerOfThree(int n) {
        return Integer.toString(n, 3).matches("10*");
    }
    
    • Power of Two

    问题描述:判断一个数是否为2的幂次,不允许使用循环或者递归。

    方法一、使用2的最大幂次来判断

    public boolean isPowerOfTwo(int n) {
        return n > 0 && 1.073741824E9 % n == 0;
    }
    

    方法二、取对数来判断

    public boolean isPowerOfTwo(int n) {
        return (Math.log10(n)/Math.log10(2)) % 1 == 0;
    }
    

     方法三、使用进制法来判断

    public boolean isPowerOfTwo(int n) {
        return n > 0 && (n & (n - 1)) == 0;
    }
    

    或者判断是否仅有一个1

    public boolean isPowerOfTwo(int n) {
        return n>0 && Integer.bitCount(n) == 1;
    }
    
    • Power of Four

    方法一、取对数来判断

    public boolean isPowerOfFour(int num) {
        return (Math.log10(num)/Math.log10(4)) % 1 == 0;
    }
    

    方法二、使用进制来判断

    public boolean isPowerOfFour(int num) {
         // 0x55555555 is to get rid of those power of 2 but not power of 4
         // so that the single 1 bit always appears at the odd position    
         return num > 0 && (num&(num-1)) == 0 && (num & 0x55555555) != 0;
    }
    

    或者直接转成4进制

    public boolean isPowerOfFour(int num) {
        return Integer.toString(num, 4).matches("10*");
    }
    
  • 相关阅读:
    使用dom4j 解析xml
    xml schema 建立xml文档
    xml dtd 约束建立xml文档
    DBCP 连接池的使用
    c++面向过程和面向对象-C++编译器是如何管理类和对象的
    c++读取文本文件
    一个范围的两个数进行数位的累加,实现对两个数num1和num2的数位和相加
    C++批量注释代码段取消注释代码段快捷键
    利用MATLAB截取一张复杂图片中想要的区域
    python学习之路系列
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/8284129.html
Copyright © 2011-2022 走看看