PAT Counting Ones

链接: https://www.nowcoder.com/questionTerminal/eb1e0fc83a25461e93b8bf2039e871b9
来源:牛客网

[编程题]Counting Ones (30)
  • 热度指数:399时间限制:1秒空间限制:65536K
  • 算法知识视频讲解
The task is simple: given any positive integer N, you are supposed tocount the total number of 1's in the decimal form of the integers from 1to N. For example, given N being 12, there are five 1's in 1, 10, 11,and 12.
输入描述:
Each input file contains one test case which gives the positive N (<=230).


输出描述:
For each test case, print the number of 1's in one line.
示例1

输入

12

输出

5
这道题目求小于等于一个数的所有数中1的个数。按位从高到低来计算,计算每一位对应的小于这个数的数的数目,相加就可以了。
if the number of the digit is bigger than 1,then the amount is (the number composed of the left digtis+1)*10^(how many digits on the right )
if the number of the digit equals 1,then the amount is (the number composed of the left digits)*10^(how many ……)+(the number composed of the right digits+1)
if smaller then 1,the amount will be (the number composed of the left digits )*10^(how many……)
we can see that all the possibilities lie in three parts.
 
// pat.cpp : 定义控制台应用程序的入口点。
//

//#include "stdafx.h"
#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn=100010;
int a[maxn];
int n,m;
int low(int x){
   int ans=1;
   x--;
	while(x-->=0){ans*=10;}

	return ans;
}
int high(int x){
    int ans=0;
	
	for(int i=n-1;i>x;i--)\
		ans=ans*10+a[i];
	
	return ans;}




int remain(){
	int ans=0;
	for(int i=m-1;i>=0;i--)
		ans=ans*10+a[i];
	return ans;

}

int main(){
	//freopen("d://jin.txt","r",stdin);
	cin>>n;
	int i=0;
	while(n!=0){
	a[i++]=n%10;
	n/=10;
		}
	m=i;
	n=m;
	
	int ans=0;
	while(m--){
		if(a[m]>1){
			
		ans+=(high(m)+1)*low(m);
			
		}
		else if(a[m]==1){ans+=high(m)*low(m)+remain()+1;
		}
        	else ans+=high(m)*low(m);
    	//cout<

你可能感兴趣的:(PAT Counting Ones)