The task is simple: given any positive integer N, you are supposed to count the total number of 1's in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1's in 1, 10, 11, and 12.
Input Specification:
Each input file contains one test case which gives the positive N (<=230).
Output Specification:
For each test case, print the number of 1's in one line.
Sample Input:
12
Sample Output:
5
我们通过分析数字的规律,找出加快计算速度的方法。
0 - 9 之间 所有数字中 出现的 1 为 1 个
0 –99 十位的1 有 10个
去掉十位后, 有10组 0~9
所以 共有 10 + 10 个
0 ~ 999 之间
百位的1 有 100 = 10^2 个
去掉百位后有 10组 : 0~99
所以共有 10^2 + 10 * ( 10^1 + 10 )
0 ~ 9999 之间千位为1的共 1000= 103 个1
去掉千位后 共有10组 0~999
所以有: 10^3 + 10*( 10^2 + 10 * ( 10^1 + 10*1 ) ) 个1
计算 0 ~ 9999…9
┣──╁ 共 n 个 9 中1的个数F9( n) 的计算方案
F9( 0 ) = 0
F9( 1) = 1
F9( 2) = 10 + 10 * F9(1)
F9( 3) = 10^2 + 10 * F9(2)
F9( n ) = 10^n-1 + 10 * F9( n-1)
计算 1 ~ abcdefg 的方法
令 1 ~ abcdefg 之间 出现 1 的个数 记为 Q( abcdefg )
设 m = len( “abcdefg”)
若 a=1 则有 F9( m-1 ) + (bcdefg+1) 个高位 1 + Q( bcdefg )
否则 a>1 ( a=0不考虑)
则有 F9( m-1) + 10^( m-1) 个 高位1 +
(a-1)* ( F9(m-1) ) + Q( bcdefg )
即: a * F9(m-1) + 10^( m-1 )个 高位1 + Q( bcdefg )
注:
F9( m-1) 是 从1 到 (m-1)个9 组成的数 之间的Q
如 F9( 2 ) 相当于 Q(99
参考代码:
#include<stdio.h>
int main()
{
int n;
int iCount=0;
int iFactor=1;
int iLowerNum=0;
int iCurrNum=0;
int iHigherNum=0;
scanf("%d",&n);
while(n/iFactor!=0)
{
iLowerNum = n%iFactor;
iCurrNum = (n/iFactor)%10;
iHigherNum = n/(iFactor *10);
switch(iCurrNum){
case 0:
iCount+=iHigherNum * iFactor;
break;
case 1:
iCount +=iHigherNum*iFactor + iLowerNum +1;
break;
default:
iCount +=(iHigherNum+1) *iFactor;
break;
}
iFactor*=10;
}
printf("%d",iCount);
return 0;
}
后面在给出详细证明!
本文提供了一种快速计算从1到任意正整数N中1的总个数的方法,并通过分析数字规律,给出具体的计算步骤及公式。
2050

被折叠的 条评论
为什么被折叠?



