如何在 Java 中以不同的基数递增数组？

问题描述投票：0回答：1

``number_of_slots``
，初始化为全0。

``number_base``

``number_of_slots``
``number_base``

``number_of_slots``

``number_base``

``````slot 2 is 0, slot 1 is 0, slot 0 is 0
slot 2 is 0, slot 1 is 0, slot 0 is 1
slot 2 is 0, slot 1 is 1, slot 0 is 0
slot 2 is 0, slot 1 is 1, slot 0 is 1
slot 2 is 1, slot 1 is 0, slot 0 is 0
slot 2 is 1, slot 1 is 0, slot 0 is 1
slot 2 is 1, slot 1 is 1, slot 0 is 0
slot 2 is 1, slot 1 is 1, slot 0 is 1
``````

``number_of_slots``

``number_base``

``````slot 1 is 0, slot 0 is 0
slot 1 is 0, slot 0 is 1
slot 1 is 0, slot 0 is 2
slot 1 is 1, slot 0 is 0
slot 1 is 1, slot 0 is 1
slot 1 is 1, slot 0 is 2
slot 1 is 2, slot 0 is 0
slot 1 is 2, slot 0 is 1
slot 1 is 2, slot 0 is 2
``````

1个回答
0

“如何在 Java 中以不同的数基递增数组？...”

``````StringBuilder s = new StringBuilder();
int x = 1234, r = 5;
while (x > 0) {
s.append(x % r);
x /= r;
}
s.reverse();
``````

``````int x = Integer.parseInt("14414", r);
``````

“...我需要创建一个函数，根据

``number_base``

...
``number_of_slots``
``number_base``

``````String convert(long x, long r) {
StringBuilder s = new StringBuilder();
while (x > 0) {
s.append(x % r);
x /= r;
}
return s.reverse().toString();
}

String add(String a, String b, int r) {
return convert(Long.parseLong(a, r) + Long.parseLong(b, r), r);
}
``````

``````long a = 1234, b = 4321, x = a + b;
System.out.printf("%5s + %6s = %6s%n", a, b, x);
String g = convert(1234, 5), h = convert(4321, 5),
`````` 1234 +   4321 =   5555