java - 获取一组相同的数字

标签 java arrays

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

例如:

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/

相关文章:

jquery - 单击 jquery 的元素数组

java - 获取 Applet 未初始化错误

java - RXJava BehaviorSubject 的 Asnyc 初始化

arrays - 从 PowerShell 数组中删除重复值

arrays - 是否可以在 Realm 中将数组转换为 Result<>?

ruby - 按Ruby中数组中对象中的值排序

c - 在 C 语言中声明数组类型是否是错误的编程习惯?

java - 在Struts2的这种情况下如何避免 "chain"?

java - Maven 不接受加密的 Nexus 密码

java - 如何/声明 google-play-services-component 时出错