gpt4 book ai didi

java - 获取一组相同的数字

转载 作者:行者123 更新时间:2023-12-02 05:34:14 24 4
gpt4 key购买 nike

我正在编写一个代码,该代码将计算有多少个具有相同数字的组。

例如:

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 个索引。是否可以输入一系列将进入不同索引的数字?

最佳答案

最简单的方法是将其转换为字符串,这样您就不必处理位值。毕竟,你只关心角色本身。

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);
}

关于java - 获取一组相同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25172423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com