计数更高的基础,没有附加字母

时间:2016-03-19 22:41:07

标签: java count numbers base

你好StackOverflowers老兄,今天我提出了一个奇怪的问题。

众所周知,有不同的计算方法(以基数计)

对于基数2(a.k.a二进制),可以计算如下

<00> 0000 =(2 ^ 3 x 0)+(2 ^ 2 x 0)+(2 ^ 1 x 0)+(2 ^ 0 x 0)= 0

0001 =(2 ^ 3 x 0)+(2 ^ 2 x 0)+(2 ^ 1 x 0)+(2 ^ 0 x 1)= 1

0010 =(2 ^ 3 x 0)+(2 ^ 2 x 0)+(2 ^ 1 x 1)+(2 ^ 0 x 0)= 2

0011 =(2 ^ 3 x 0)+(2 ^ 2 x 0)+(2 ^ 1 x 1)+(2 ^ 0 x 1)= 3

......等等......

当我们达到高于10的基数时,例如16(a.k.a十六进制)我们用字母来表示值:

例如:

200 base 16 = C8 ---&gt; http://www.binaryhexconverter.com/decimal-to-hex-converter(如果你不相信我;))

但是,我们如何计算高于字母允许的基数? (基地37 +)

我写了一个简单的java程序来说明我的观点:

public class Testing {
public static void main(String[] args) {
    for (int base = 1;base<=50;base++){
        System.out.println("===========================Base " + base + "===============================");
        for (int value=1; value<=50; value++){
              System.out.println(value + " base " + base + " is equal to: " + Integer.toString(value, base));
            }
        }
    }
}

以下是我的程序输出的一些片段:

40 base 36 is equal to: 14
41 base 36 is equal to: 15
42 base 36 is equal to: 16
43 base 36 is equal to: 17
44 base 36 is equal to: 18
45 base 36 is equal to: 19
46 base 36 is equal to: 1a
47 base 36 is equal to: 1b
48 base 36 is equal to: 1c
49 base 36 is equal to: 1d
50 base 36 is equal to: 1e

28 base 37 is equal to: 28
29 base 37 is equal to: 29
30 base 37 is equal to: 30
31 base 37 is equal to: 31
32 base 37 is equal to: 32
33 base 37 is equal to: 33
34 base 37 is equal to: 34
35 base 37 is equal to: 35
36 base 37 is equal to: 36
37 base 37 is equal to: 37
38 base 37 is equal to: 38
39 base 37 is equal to: 39
40 base 37 is equal to: 40
41 base 37 is equal to: 41
42 base 37 is equal to: 42
43 base 37 is equal to: 43
44 base 37 is equal to: 44
45 base 37 is equal to: 45
46 base 37 is equal to: 46
47 base 37 is equal to: 47
48 base 37 is equal to: 48
49 base 37 is equal to: 49
50 base 37 is equal to: 50

正如你所看到的,37岁以上的基础不起作用。

有没有解决这个问题?谢谢!

2 个答案:

答案 0 :(得分:3)

Character.MAX_RADIX等于36(10位数和26个字母)。

如果要为基数使用更高的值,则必须编写自己的方法。这不应该太难。我建议修改Integer.toString(int, int)的源代码。此方法的代码使用此数组:

final static char[] digits = {
    '0' , '1' , '2' , '3' , '4' , '5' ,
    '6' , '7' , '8' , '9' , 'a' , 'b' ,
    'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
    'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
    'o' , 'p' , 'q' , 'r' , 's' , 't' ,
    'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};

答案 1 :(得分:0)

试试这个。

public static String DIGITS = "0123456789abcdefghijklmnopqrstuvwxyz@!#$%&;:";

public static String toString(int i, int base) {
    StringBuilder sb = new StringBuilder();
    for (; i > 0; i /= base)
        sb.append(DIGITS.charAt(i % base));
    if (sb.length() == 0)
        sb.append(0);
    return sb.reverse().toString();
}