java 统计数字


package wangChaoPA实习工作练习.com.java基础算法;

import java.util.Scanner;

/**
 *
 * <p>
 * 描述该类情况 {@link 代表跟谁有关系}
 * </p>
 *
 * @author 王超
 * @since 1.0
 * @date 2017年3月22日 下午1:33:00
 * @see 新建|修改|放弃
 * @see wangChaoPA实习工作练习.com.java基础算法.CountDigit
 *      问题:把前n(n<10000)个整数顺次写在一起:12345678910111213141516....数一数0至9出现的次数
 *      输出10个整数,分别是0,1,2..至9出的个数 解题思路:把数字转换成字符数组 进而遍历每一个数中的每一位 进行统计
 */

public class CountDigit
{
    private static Scanner input = new Scanner(System.in);

    public static void main(String[] args)
    {
        int zer = 0, fir = 0, sec = 0, thi = 0, fou = 0, fiv = 0, six = 0,
                sev = 0, eig = 0, nin = 0;
        Integer n = input.nextInt();
        for (Integer i = 1; i <= n; i++)
        {
            String temp = i.toString();
            char tempArray[] = temp.toCharArray();
            for (int j = 0; j < tempArray.length; j++)
            {
                if (tempArray[j] == '0')
                {
                    zer++;
                }
                else if (tempArray[j] == '1')
                {
                    fir++;
                }
                else if (tempArray[j] == '2')
                {
                    sec++;
                }
                else if (tempArray[j] == '3')
                {
                    thi++;
                }
                else if (tempArray[j] == '4')
                {
                    fou++;
                }
                else if (tempArray[j] == '5')
                {
                    fiv++;
                }
                else if (tempArray[j] == '6')
                {
                    six++;
                }
                else if (tempArray[j] == '7')
                {
                    sev++;
                }
                else if (tempArray[j] == '8')
                {
                    eig++;
                }
                else
                {
                    nin++;
                }

            }
        }
        System.out.println("0:" + zer);
        System.out.println("1:" + fir);
        System.out.println("2:" + sec);
        System.out.println("3:" + thi);
        System.out.println("4:" + fou);
        System.out.println("5:" + fiv);
        System.out.println("6:" + six);
        System.out.println("7:" + sev);
        System.out.println("8:" + eig);
        System.out.println("9:" + nin);
        input.close();
    }

}

原文地址:https://www.cnblogs.com/qingtianBKY/p/6599773.html