我正在尝试解决一些基本的java问题:
我有一个像 int[] x = { 12, 24, 33 }; 这样的数组。
我需要将它分成像 {1, 2, 2, 4, 3 这样的数字,3}
,然后按以下方式计算重复数字:1:1, 2:2, 3:2, 4:1。
到目前为止,我得到了这个代码,但我无法将数字保存到数组中。 有人可以帮助我吗?
public class targil_2_3 {
public static void main(String[] args) {
int[] x = { 12, 24, 33 };
int[] ara = new int[x.length * 2];
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < 2; j++) {
ara[j] = x[i] % 10;
x[i] = x[i] / 10;
System.out.println(ara[j]);
}
}
}
}
最佳答案
您不需要存储单个数字,您只需存储数字计数。假设您正在使用 10 个基数,那么代码可能类似于
public static void main(String[] args) {
int[] x = { 12, 24, 33, 0, 10, 555 };
int[] count = new int[10];
for (int i = 0; i < x.length; i++) {
int num = x[i];
if (num == 0) {
count[0]++;
continue;
}
while (num > 0) {
count[num % 10]++;
num = num / 10;
}
}
System.out.println(Arrays.toString(count));
}
输出为
[2, 2, 2, 2, 1, 3, 0, 0, 0, 0]
关于java - 将数组中的多个数字分解为数字并计算重复数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39888711/