PAT 1049. Counting Ones (30)

1049. Counting Ones (30)

时间限制
10 ms
内存限制
32000 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

提交代码



法1:暴力法(22/30)。当时想不出更好的方法,22分已足够。


#include<stdio.h>
int cnt;
int main()
{	
	int	i,n,tmp;
        //freopen("G:\\in.txt","r",stdin);
	while(scanf("%d",&n)!=EOF){
		cnt=0;        //全局变量初始化
		for(i=1;i<=n;i++){
			int t=i;  //注意i作为增量,不要直接修改i,造成死循环。。
			do{
				tmp=t%10;
				t=t/10;
				if(tmp==1)
					cnt++;
			}while(t!=0);
		}
		printf("%d\n",cnt);	
	}
    return 0;
}


法2: 分析数学规律 (30/30)


对两位数进行分析,我们发现,

个位数出现1的次数不仅和个位数字有关,还和十位数有关:如果N的个位数大于等于1,则个位出现1的次数为十位数的数字加1;如果N的个位数为0,则个位出现1的次数等于十位数的数字。

十位数上出现1的次数不仅和十位数有关,还和个位数有关:如果十位数字等于1,则十位数上出现1的次数为个位数的数字加1;如果十位数大于1,则十位数上出现1的次数为10。     


以此类推的规律如下:

          若当前权值base位是0, 那么1的个数只取决于高位:high*base

      若当前权值base位是1, 那么1的个数取决于高位和低位:high*base+low+1

      若当前权值base位>=2,那么1的个数只取决于高位:(high+1)*base


#include<stdio.h>
int cnt,base;
int main()
{	
	int	n,high,low,now;
    //freopen("G:\\in.txt","r",stdin);
	while(scanf("%d",&n)!=EOF){
		cnt=0;base=1;        //全局变量初始化
		while(n/base!=0){
			low=n%base;         //当前权值的低位
			now=(n/base)%10;   //当前权值位
			high=(n/base)/10; //当前权值的高位
			if(now==0)
				cnt+=high*base;
			else if(now==1)
				cnt+=high*base+low+1;
			else
				cnt+=(high+1)*base;
			base*=10;
		}
		printf("%d\n",cnt);
	}
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值