java 统计数字个数_统计数字问题(Java)
Description
一本書的頁碼從自然數1 開始順序編碼直到自然數n。書的頁碼按照通常的習慣編排,每個頁碼都不含多余的前導數字0。例如,第6 頁用數字6 表示,而不是06 或006 等。數字計數問題要求對給定書的總頁碼n,計算出書的全部頁碼中分別用到多少次數字0,1, 2,…,9。給定表示書的總頁碼的10 進制整數n (1≤n≤10^9) 。計算書的全部頁碼中分別用到多少次數字0,1,2,…,9。
Input
輸入數據只有1 行,給出表示書的總頁碼的整數n。
Output
輸出數據共有10行,在第k行輸出頁碼中用到數字k-1 的次數,k=1,2,…,10。
Sample Input
11
Sample Output
1
4
1
1
1
1
1
1
1
1
import java.util.Scanner;
public class Main {
public static int num[] = new int[10];
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = 0;
n = cin.nextInt();
Count(n); // 統計00..00 - n之間的0-9數字的個數
num[0] -= del_zero(get_length(n)); // 減去比如0001,0066這種多余的0的個數
for (int i = 0; i < 10; i++)
System.out.println(num[i]);
}
// 獲取數字的長度
public static int get_length(int num){
return (int)Math.log10(num) + 1;
}
// 獲取數字的第一位數
public static int get_head(int num){
return num / (int) Math.pow(10, get_length(num) - 1);
}
// 獲取數字的余數
public static int get_remainder(int num){
return num % (int) Math.pow(10, get_length(num) - 1);
}
/* 統計00..00~n之間多余的0
比如000 - 999可以看成
0 00 - 0 99, 100 - 100
0 1 - 0 9, 10 - 99
*/
public static int del_zero(int length){
if (length == 1)
return 1;
return del_zero(length - 1) + (int) Math.pow(10, length - 1);
}
// 統計00..00 - n之間0-9數字的個數
public static void Count(int n){
/* f(n) = n * 10^(n-1),
f(n)是n個0到n個9之間0-9的個數
比如f(2) = 20
表示00 - 99之間0有20個, 1有20個......9有20個
*/
/* 比如34789, 分成3組0000 - 9999
0 0000 - 0 9999
1 0000 - 1 9999
2 0000 - 2 9999
*/
for (int i = 0; i < 10; i++){
num[i] = num[i] + get_head(n) * (get_length(n) - 1) * (int) Math.pow(10, (get_length(n) - 2));
}
/* 比如34789, 首位0, 1, 2分別加上10000個
00000 - 09999
10000 - 19999
20000 - 29999
*/
for (int i = 0; i < get_head(n); i++){
num[i] = num[i] + (int) Math.pow(10, get_length(n) - 1);
}
// 比如34789, 首位3, num[3]加上余數4789和特殊情況30000
num[get_head(n)] += get_remainder(n) + 1;
// 如果余數為0, 比如 40000, num[0] 得加上長度-1,并且余數為0時結束遞歸
if (get_remainder(n) == 0) {
num[0] += get_length(n) - 1;
return;
}
/* 比如4000589這種情況, 直接余數遞歸回漏掉中間的0
所以num[0]得加上(7 - 1 - 3) * (589 + 1)
*/
if (get_length(n) - 1 != get_length(get_remainder(n))) {
num[0] += (get_length(n) - 1 - get_length(get_remainder(n))) * (get_remainder(n) + 1);
}
// 用余數接著遞歸
Count(get_remainder(n));
}
}
總結
以上是生活随笔為你收集整理的java 统计数字个数_统计数字问题(Java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java timestamp是什么类型_
- 下一篇: 好听又幸运顺利的网名90个