Determining whether a positive integer is an integer power of 2




Foreword

Previous finished common methods commonly used class BigInteger, and happened to see an interesting topic, you can also just use what BigInteger, so I wrote this one

I, entitled

Title: determining whether a positive integer is an integer power of 2 (e.g. 4 is 2 to the power 2, returns true; 5 is not an integer power of 2, then return false). Performance requirements as high as possible.

Second, the problem solution

Ideas:

I have here a total of three solutions, namely, multiplication, division, bit computing.

Specific ideas have been written comment on the method, which may be attached to the IDE to run the code view.

Note: Do not care about my Chinese name of the class, I just for convenience only.

Code:

/**
 * @题目 判断一个正整数是否是2的整数幂。要求性能尽可能高。
 *
 * @author: ChangSheng
 * @date:   2020年1月21日 下午5:59:29
 */
public class 判断一个正整数是否是2的整数幂 {

    public static void main(String[] args) {
        System.out.println(usingMultiplication(1024)); // true
        System.out.println(usingDivision(1024)); // true
        System.out.println(usingBit(1024)); // true
        System.out.println(usingBigInteger(new BigInteger("1024"))); // true
    }

    /**
     * @思路 使用乘法,如果i不断乘2等于num,则是2的整数次幂。
     */
    public static boolean usingMultiplication(int num){
        int i = 1;
        while (i <= num) {
            if (i == num) return true; // 相等
            i <<= 1; // 左移运算符,等同于 i = i << 1 和 i *= 2;
        }
        return false;
    }

    /**
     * @思路 使用除法,如果num不断除2有余数,则不是2的整数次幂。
     */
    public static boolean usingDivision(int num) {
        while (num > 1) {
            if (num % 2 == 1) return false; // 有余数
            num >>= 1; // 右移运算符,等同于 num = num >> 1 和 num /= 2;
        }
        return true;
    }

    /**
     * @思路 使用位运算符&。性能比上面两个方法更高
     * 以下2的n次幂都用m代替。
     * m的二进制都是1开头0结尾,若将m减1,则该数二进制全为1。如8的二进制为:1000,8减1二进制为:111。其余同理
     * 此时,如用与运算符&计算2的n次幂 与 2的n次幂减1,可得到1000 & 111 等于0。
     * 综合上述,如果m & m-1 等于 0,则该数为2的n次幂,否则不是。
     */
    public static boolean usingBit(int num) {
        return (num & num - 1) == 0;
    }

    /**
     * @问题 万一需要判断的时一个很大的数的呢?但上述方法却不能传太大的数。
     * @解决思路 使用BigInteger进行位运算符or,思路同usingBitAnd()方法一样
     * @param num 需要判断的数字
     * @return 如果传入值是2的n次幂时,返回true。
     */
    public static boolean usingBigInteger(BigInteger num) {
        BigInteger subtract = num.subtract(BigInteger.ONE); // num - 1
        BigInteger and = num.and(subtract); // 与运算符&运算
        return and.equals(BigInteger.ZERO); // 使用equals()方法比较相等
    }
}


Related Links

[Java] Common classes (5) java.math.BigInteger conventional method (the method of a conventional simple text after studying the BigInteger)

Published 99 original articles · won praise 105 · Views 9359

Guess you like

Origin blog.csdn.net/weixin_44034328/article/details/104065337