1049. Counting Ones (30)

本文提供了一种快速计算从1到任意正整数N中1的总个数的方法,并通过分析数字规律,给出具体的计算步骤及公式。

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;
}

后面在给出详细证明!

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值