一个完美的鲁棒的数字打印程序

在这里我们只打印long的最小的数字 -9223372036854775808的16进制

import java.math.BigInteger;

public class PrintInt {
    private static final String DIGIT_TABLE = "0123456789abcdef";
    private static final int MAX_BASE = DIGIT_TABLE.length();
    /**
     * 最高的为16进制
     * @param args
     */
    public static void main(String[] args) {

        BigInteger N = new BigInteger(Long.toString(Long.MIN_VALUE));
        printInt(N, 16);
    }

    private static void printIntRec(BigInteger n, int base) {
        if (n.compareTo(new BigInteger(Integer.toString(base))) >= 0)
            printIntRec(n.divide(new BigInteger(Integer.toString(base))), base);
        System.out.print(DIGIT_TABLE.charAt((n.mod(new BigInteger(Integer.toString(base)))).intValue()));
    }

    public static void printInt(BigInteger n, int base) {
        if (base <= 1 || base > MAX_BASE)
            System.out.println("Cannot print in base " + base);
        else {
            if (n.compareTo(new BigInteger(Integer.toString(0))) < 0) {
                n = n.abs();
                System.out.print("-");
            }
            printIntRec(n, base);
        }
    }
}

你可能感兴趣的:(递归算法)