Count the number of different digits appear

Description Title:
  Given a k-bit integer N = dk-1 * 10k- 1 + ... + d1 * 101 + d0 (0 <= di <= 9, i = 0, ..., k-1, dk -1> 0), write a program to count the number of each different digit arise. For example: given N = 100311, there are two 0,3 1 2, and 1 3

Ideas:

  First, the formula for long scared !!! But hey read the title, it means to make a number you count the number of times this number appears in different single digits, the record number of thinking is very common, it is to into a given digital characters these characters stored in the list, each spray patriotic to a same numerical value is incremented, and finally the list collective output

 Enter a description:

Of no more than 1000 bit positive integer N

Output Description:

N different for each digit, to D: N format of the output of the digit line D and the number of occurrences N, is required ascending output D

Example:

Enter 199 003

Output:

0:2

1:1

3:1

9:2

Code shows:

package com.bittech;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * package:com.bittech
 * Description:NumCounts
 * @date:2019/6/3
 * @Author:weiwei
 **/
public class NumCounts {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入数字: ");
        String N = sc.next();
        char [] chars = N.toCharArray();
        /**
         * 创建list,10个item(0-9),每个item得值表示数字的个数,
         */
        List<Integer> list = new ArrayList<>();
        for(int i =0;i<10;i++){
            list.add(0);//初始化为0
        }
        for(int i = 0;i<chars.length;i++){
            //每次遇到一个数字,数字就加1
            list.set(chars[i]-'0',list.get(chars[i]-'0')+1);
        }
        for(int i =0;i<list.size();i++){
            if(list.get(i)>0){
                System.out.println(i+":"+list.get(i));
            }
        }
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_43224539/article/details/90751193