[英]Break multiple numbers in array into digits and count the repeating numbers
我正在尝试解决一些基本的Java问题:
我有一个像int[] x = { 12, 24, 33 };.
的数组int[] x = { 12, 24, 33 };.
我需要将其分解为{1, 2, 2, 4, 3 ,3}
1,2,2,4,3,3 {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]
import java.util.Arrays;
import java.util.Map;
import static java.util.stream.Collectors.*;
public class Use {
public static void main(String[] args) {
int[] x = { 12, 24, 33 };
Map<Integer, Long> result = Arrays.stream(x).boxed()
.map(String::valueOf)
.collect(joining())
.chars().boxed()
.collect(groupingBy(Character::getNumericValue, counting()));
System.out.println(result); //prints {1=1, 2=2, 3=2, 4=1}
}
}
int[]
转换为Stream<Integer>
(对于每个元素) Stream<Integer>
转换为Stream<String>
Stream<String>
减少为String
Stream<Integer>
(为每个数字) Map
中每个数字的出现 我们只有10个十进制数字,范围是0到9,[0..9]
所以我们创建一个长度为10的数组,例如count:
int count[] = new int[10];
for(int i = 0 ; i < x.length ; i++){
if( x[i] == 0 ){
count[0]++;
continue;
}
while(x[i]!=0){
int index = x[i] % 10;
count[index]++;
x[i] /= 10;
}
}
那么我们将在count数组中有位数,因此我们可以打印它:
for(int i = 0 ; i < 10 ; i++)
System.out.println(i+" : "+count[i]);
如果您的数据很大,最好使用Map,有很多方法可以做到这一点
数字是0-9。 建立一个大小为10的计数器数组,并对在计数器数组的正确索引中提取的每个数字进行计数(“ counter [digit] ++”)。
编辑:当然,最后,您可以基于计数器数组构建所需的结果数组。
例如:result [0] =“ 0:” + counter [0];“
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.