java - 如果数组中存在一组特定的数字,我该如何计数

标签 java algorithm java-8

假设我有一个数字 123。我需要看看我是否得到了 1 到 9 的所有数字,包括 0。数字 123 有三个数字:1、2 和 3。然后我将它乘以 2 得到 246 (我得到数字 2、4、6)。然后我将它乘以 3,得到 369。我一直进行增量乘法,直到得到所有数字。

我的方法如下:

public int digitProcessSystem(int N) {
 String number = Integer.toString(N);
 String [] arr = number.split("");
// List <Integer> arr2 = new ArrayList<>();
 for (Integer i = 0; i < arr.length; i++) {
     try {

         arr2[i] = Integer.parseInt(arr[i]);
     } catch (NumberFormatException e) {
         }
     }

 count =0;
 boolean contains = IntStream.of(arr2).anyMatch(x -> x == 1|| x==2 ||x ==  3|| x==4|| x == 5|| x==6 ||x == 7|| x==8||x == 9|| x==0);

}

我真的不知道如何继续对上面第一条路径中不匹配的数字进行 boolean 运算,因为我肯定会在上面的 boolean 搜索中得到所有数字中的任何一个。如果存在某些特定数字而有些不存在,我如何才能得到它,以便我可以乘以实际数字来搜索在第一次试验中未找到的数字;就像我一开始定义的那样。

最佳答案

您可以将其包装到一个 while 循环中,并将数字包含到一个 Set 中。一旦集合的大小为 10,所有数字都出现在数字中。我还建议使用 long 而不是 int 否则你会得到错误的结果或遇到异常。这是一些示例代码:

private static long digitProcessSystem(long N) {
    long numberN = N;
    String number = Long.toString(N);
    // calculate 10 digits number here yet
    if (number.length() < 10) {
        // using the smallest possible number with each digit
        // By using this number we are most likely allmost at the result
        // This will increase the performance for small digits heavily.
        long divider = 1023456789L / numberN;
        numberN *= divider;
    }
    number = Long.toString(numberN);
    String[] arr = number.split("");
    Set<String> input = new HashSet<>(Arrays.asList(arr));
    while(input.size() != 10){
        // add N to number
        numberN += N;
        // Parse the new number
        number = Long.toString(numberN);
        // split
        arr = number.split("");
        // clear set
        input.clear();
        // Add the new numbers to the set. If it has the size 10 now the loop will stop and return the number.
        input.addAll(Arrays.asList(arr));
    };
    return numberN;
}

public static void main(String[] args) {
    System.out.println(digitProcessSystem(123));
}

输出:

1023458769

关于java - 如果数组中存在一组特定的数字,我该如何计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36514023/

相关文章:

java - 指向循环 TextView 和按钮

java - 跨 JVM 检测

java - (Java) 使用子类时代码可以工作,但使用父类(super class)会导致空指针错误?

javascript - 获取对象数组中重复键的值

java - 在空引用上创建方法引用不会引发异常

java - 菜单选项卡不响应

arrays - 数组自下而上获取所有 child 的总和

python - 在递归中使用 yield 平衡内存和性能

java - 如何使用流对这个 HashMap 进行排序,同时对其进行展平/分组?

java - 如何使用函数式接口(interface)组织 java 8 代码