1049 Counting Ones (30 分) 分析规律 较为不易

1049 Counting Ones (30 分)

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 (≤2​30​​).

Output Specification:

For each test case, print the number of 1's in one line.

Sample Input:

12

Sample Output:

5

千万不要被吓到了,害怕而不敢分析。其实就是简单排列组合,以每位为1为中心。

千万注意,每次只统计某一位上1在[1,N]所有数字中出现的次数,仅仅是该位上的,并没有统计其他位上的,因此不会导致重复。

★★eg:N=13 
    个位1:{1,11}  2个
    十位1:{10,11,12,13} 4个
    共2+4=6个
    其中11用了两次,看似重复了,其实并没有,因为第一次统计的是11个位上的1,第二次统计11十位上的1。
    正好统计两次,而11确实有2个1呀

#include<bits/stdc++.h>
using namespace std;
int main(){
	int n,m,p=1,ans=0,high,low,self;
	cin>>n;
	m=n;//备份 以便求高低位 
	while(n){
		self=n%10;//当前位 
		high=m/(p*10);//计算高位 
		low=m%p;//计算低位 
		if(self<1) ans+=high*p;//小于1 高位*数量级 
		else if(self==1) ans+=high*p+(low+1);// 等于1  高位*数量级+(低位+1)    后面的小部分单独考虑为(低位+1) 
		else ans+=(high+1)*p;	// 大于1  (高位+1)*数量级 
				
		p*=10;//当前数量级+1
		n/=10;
	}
	cout<<ans;
	return 0;
}

 

 

然而其实PAT比较仁慈,直接暴力竟然有22分。。。

#include<bits/stdc++.h>
using namespace std;

int count(int n){
	int num=0;
	while(n){
		if(n%10==1) num++;
		n/=10;
	}
	return num;
}

int main(){
//	freopen("in.txt","r",stdin);
	int n,ans=0;
	cin>>n;
	for(int i=1;i<=n;i++){
		ans+=count(i);
	} 
	cout<<ans;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值