数字计数问题(Java实现)
数字计数问题
一本书的页码从自然数 1 开始顺序编码到 N (N≥100000)。页码按照通常的习惯编 排,即每个页码不能含多余的前倒数 0,例如,、第 6 页的页码为 6,不能是 06、006 等。 数字计数问题要求从键盘输入页数 N,输出全书页码中分别用到 0、1、2、3、4、5、6、 7、8、9 的次数。
import java.util.Arrays; import java.util.Scanner; public class NumberCount { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); sc.close(); int[] count = solve(num); for (int i = 0; i <= 9; i++) { System.out.print("数字" + i + "用到了:"); System.out.println(count[i] + "次"); } } public static int[] solve(int num) { int[] count = new int[10]; Arrays.fill(count, 0); //value数组用于存储数字的每一位,由低位到高位存储。(123——>3,2,1) int[] value = trans(num); //max是给定数字的最高位 int max = value.length; // 遍历数字的每一位 for (int i = 0; i < max; i++) { // 对小于每一位上的数字值的数字进行计数 for (int j = 1; j <= value[i]; j++) { // 对小于当前位的数字值计数次数为:10的当前位数的次方 if (j < value[i]) { count[j] += Math.pow(10, i); } // 对当前位的数字值对应的数字计数为:num对10的i次方求模,再加一 else { count[j] += (int) (num % Math.pow(10, i)) + 1; } } } // 遍历数字的每一位,最高位不遍历 for (int i = 0; i < max - 1; i++) { // 遍历0-9数字 for (int j = 0; j <= 9; j++) { // 对count[]数组每一个元素进行计数 count[j] += ((int) (num / Math.pow(10, i + 1)) * Math.pow(10, i)); } } return count; } //trans函数将给定数字转换为int数组保存,且由低位到高位排列(数字123转换为数组value[],且值依次为3,2,1) public static int[] trans(int num) { String str = String.valueOf(num); char[] array = str.toCharArray(); int[] value = new int[array.length]; for (int i = 0; i < array.length; i++) { value[i] = (int) array[array.length - 1 - i] - (int) ('0'); } return value; } }