java 我怎样做一个程序来计算1到100之间的每一个数字的出现次数呢?

fquxozlt  于 2023-01-19  发布在  Java
关注(0)|答案(6)|浏览(237)

我正在编写一个程序,计算1到100之间的每个数字(0 - 9)出现的次数,最后它会说:

The digit 0 showed up ____ times between 1-100
The digit 1 showed up ____ times between 1-100

等等。
这是我的

public class CountEachDigit {

    public static void main(String[] args) {

        int counter =0;

        int[] digit = new int[10];

        for (int i=1;i<=100;i++) {
    
            for (int j=0;j<=9;j++){
  
                try{
                    String a = String.valueOf(i);
                    String b = String.valueOf(j);
                    if (b.equals(a.charAt(0)))
                            counter++;
                            digit[j]=counter;
                } catch (Exception e){
                    continue;
                }

                try{
                    String a = String.valueOf(i);
                    String b = String.valueOf(j);
                    if (b.equals(a.charAt(1)))
                        counter++;
                        digit[j]=counter;
                } catch (Exception e){
                    continue;
                }

                try{
                    String a = String.valueOf(i);
                    String b = String.valueOf(j);
                    if (b.equals(a.charAt(2)))
                        counter++;
                        digit[j]=counter;
                } catch (Exception e){
                    continue;
                }
    
            }
        }

        for (int j =0;j<=9;j++){
            System.out.println("The number "+j+" appears "+digit[j]+" times between 1 - 100.");
        }
    }
}

我试着将每个数字的charat改为一个字符串,以便使用try和catch来计算出现的次数。目前为止没有任何结果。

z0qdvdin

z0qdvdin1#

您不需要字符串操作。您必须使用x % 10获取最后一位数字,然后使用x \= 10删除最后一位数字。

public class CountEachDigit {

    public static void main(String... args) {
        final int lo = 1;
        final int hi = 100;
        int[] digits = countDigits(lo, hi);

        for (int i = 0; i < 10; i++)
            System.out.format("The number %d appears %d times between %d - %d.\n", i, digits[i], lo, hi);
    }

    private static int[] countDigits(int lo, int hi) {
        int[] digits = new int[10];

        for (int i = lo; i <= hi; i++) {
            if (i == 0) {
                digits[0]++;
            } else {
                int val = i;

                do {
                    digits[val % 10]++;
                } while ((val /= 10) > 0);
            }
        }

        return digits;
    }

}

演示:

The number 0 appears 11 times between 1 - 100.
The number 1 appears 21 times between 1 - 100.
The number 2 appears 20 times between 1 - 100.
The number 3 appears 20 times between 1 - 100.
The number 4 appears 20 times between 1 - 100.
The number 5 appears 20 times between 1 - 100.
The number 6 appears 20 times between 1 - 100.
The number 7 appears 20 times between 1 - 100.
The number 8 appears 20 times between 1 - 100.
The number 9 appears 20 times between 1 - 100.
vmjh9lq9

vmjh9lq92#

有一个int[10]的数组来计算每个数字的出现次数。
然后让一个函数遍历一个字符串,对于它找到的每个数字,增加数组中正确的字段。
然后循环从1到100的数字,将数字转换为字符串并将其输入函数。
最后打印数组值。
在代码中可能类似于

public class Test {

    static int[] occurrences = new int[10];
    
    static void checkOccurrences(String s) {
        for (char c: s.toCharArray()) {
            if (Character.isDigit(c)) {
                occurrences[ c - '0' ]++;
            }
        }
    }
    
    public static void main(String[] args) {
        for (int i=1; i<=100; i++) {
            String s = String.valueOf(i);
            System.out.println("checking "+s);
            checkOccurrences(s);
        }
        System.out.println(Arrays.toString(occurrences));
    }
}

然后打印出来

checking 1
checking 2
checking 3
...
checking 99
checking 100
[11, 21, 20, 20, 20, 20, 20, 20, 20, 20]
n9vozmp4

n9vozmp43#

如果您或未来的读者想了解流方法(我对此表示怀疑),下面是我为了好玩而做的事情:在[1 - 100]范围内进行流传输,转换并Map为字符串,在每个字符处拆分每个字符串,例如"42"变为"4" and "2"流,使用数字作为关键字并使用出现次数作为值进行收集以Map,最后打印。

import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

// ...

public static void main(String[] args) {
    IntStream.rangeClosed(1, 100)
             .mapToObj(String::valueOf)
             .flatMap(s -> Arrays.stream(s.split("")))
             .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
             .forEach((k,v) -> System.out.printf("The digit %s showed up %d times between 1-100%n", k, v));
}
6psbrbz9

6psbrbz94#

除了将一个数字转换为字符串,然后循环遍历它的数字之外,你还可以将余数除以10,也就是最后一位数字,然后将数字除以10,将它向右“移位”,例如45 % 10 == 545 / 10 == 4
退出while循环后,number是一位数,因此必须再次计算该数字。

public class CountEachDigit {

    public static void main(String[] args) {

        int[] digits_count = new int[10];
        int min = 1;
        int max = 100;

        for (int i = min; i <= max; ++i) {
            int number = i;

            while (number > 9) {
                int last_digit = number % 10;
                digits_count[last_digit] += 1;

                number /= 10;
            }

            digits_count[number] += 1;
        }

        for (int i = 0; i < 10; i++) {
            int count = digits_count[i];
            System.out.println("Digit " + i + " appears " + count + " times in range [" + min + ", " + max + "]");
        }

    }
}
8fsztsew

8fsztsew5#

使用字符串:

for (int i = 1; i <= 100; i++) {
    String num = String.valueOf(i); 
    for(int j=0;j<num.length();j++){
//substracting 0 to get the integer value
        counts[num.charAt(j)-'0']++;
    }
}
for (int i = 0; i < 10; i++) {
    System.out.println("The digit " + i + " showed up " + counts[i] + " times between 1-100.");
}
c2e8gylq

c2e8gylq6#

您可以使用通过流式传输和在Map中采集来执行此操作。

  • 分配Map以保存计数
  • 从1到100(包括1和100)对值进行流处理
  • 在MapMulti内
  • 使用余数%运算符获取最后一位数字
  • 接受数字并将其放入流中
  • 通过除以10暴露下一个数字
  • 现在收集Map中的数字,当它们出现时创建一个频率计数。每个数字将是键,值将是计数。
Map<Integer, Integer> counts = IntStream.rangeClosed(1, 100)
         .mapMulti((val, consumer) -> {
             while (val > 0) {
                 consumer.accept(val % 10);
                 val /= 10;
             }
         }).boxed()
         .collect(Collectors.toMap(i -> i, i -> 1, Integer::sum));

 counts.forEach((digit, count) -> System.out
               .println(digit + " occurs " + count + " times."));

印刷品

0 occurs 11 times.
1 occurs 21 times.
2 occurs 20 times.
3 occurs 20 times.
4 occurs 20 times.
5 occurs 20 times.
6 occurs 20 times.
7 occurs 20 times.
8 occurs 20 times.
9 occurs 20 times.

相关问题