我正在处理一个代码,该代码将计算具有相同数字的群组的数量。
例如:
11022 = 2 groups with the same number
1100021 = 2 groups with the same number
12123333 = 1 group with the same number
到目前为止,我已经达到了这个代码:
package Numbers;
import java.util.*;
public class Numbers{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int strI ;
strI = scan.nextInt();
int[] a = {strI};
System.out.println(sum(a));
System.out.println("length = "+a.length);
}
public static in sum(int[] a){
int sum = 0;
int last = 0;
for (int i = 0; i < a.length - 1; i++){
if(a[i] == a[i + 1] && last != a[i + 1]){
sum++;
}
last = a[i];
}
return sum;
}
}
我的问题是输入的号码将注册为1个索引。是否可以输入一系列将转到不同索引的数字?
答案 0 :(得分:1)
这是最简单的方法,将其转换为字符串,这样您就不必处理场所价值。毕竟,你只关心角色本身。
public static void main(String[] args){
// Get number n... Assuming n has been set to the int in question
int n = ...; //Fill in with whatever int you want to test
String s = n + "";
char same = ' ';
int consec = 0;
for(int i = 0; i < s.length() - 1; i++){
if(s.charAt(i) == s.charAt(i+1)){
if(same == ' ')
consec++;
same = s.charAt(i);
}
else{
same = ' ';
}
}
System.out.println(consec);
}
答案 1 :(得分:1)
首先,您可以使用类似
的内容获取连续数字的计数public static int sum(int a) {
String strI = String.valueOf(a);
int count = 0;
boolean inRun = false;
for (int i = 1; i < strI.length(); i++) {
if (strI.charAt(i - 1) == strI.charAt(i)) {
if (inRun) {
continue;
}
inRun = true;
count++;
} else {
inRun = false;
}
}
return count;
}
public static void main(String[] args) {
int[] arr = { 11022, 1100021, 12123333 };
for (int val : arr) {
int count = sum(val);
String group = "groups";
if (count == 1) {
group = "group";
}
System.out.printf("%d = %d %s with the same number%n", val, count, group);
}
}
输出是请求的
11022 = 2 groups with the same number
1100021 = 2 groups with the same number
12123333 = 1 group with the same number
关于你的第二个问题,你可以将Integer
读成List
- Java数组是不可变的,
List<Integer> al = new ArrayList<>();
Scanner scan = new Scanner(System.in);
while (scan.hasNextInt()) {
al.add(scan.nextInt());
}
Integer[] arr = al.toArray(new Integer[0]);
System.out.println(Arrays.toString(arr));