PAT 1049 Counting Ones (30)

本文探讨了在给定正整数N的情况下,如何高效计算从1到N中所有整数的十进制形式中1的总数。通过分析每一位1出现的规律,提出了一种优化算法,该算法考虑了当前位数、左边数和右边数的影响,从而减少了计算复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


#include<iostream>
#include<vector>
using namespace std;
int main(){
  int n;
  while(1){
  cin>>n;
  if(n==-1) break;
  vector<int> v;
  v.push_back(0);
  for(int i=1; i<=n; i++){
    int cnt=0, temp=i;
    while(temp){
        if(temp%10==1) cnt++;
        temp/=10;
    }
    v.push_back(v[i-1]+cnt);
  }
  cout<<v[n]<<" "<<f(n)<<endl;
  }
  return 0;
}

 

观察可以发现每一位1出现的次数和当前位左边的数有关 也和右边的数有关;
计算1的个数还与当前为的数有关
当前位为0的时候
当前位为1
当前位为12..9

 1 #include<iostream>
 2 #include<vector>
 3 #include<cmath>
 4 using namespace std;
 5  
 6 int main(){
 7   int n;
 8   cin>>n;
 9   int cnt=0, cpy=n;
10   vector<int> v;
11   while(cpy){//求n的每一位数
12     v.push_back(cpy%10);
13     cpy /= 10;
14   }
15   cnt = n/10;
16   if(n%10>=1) cnt++;
17   int idx=2, coe=10;
18   while(idx<=v.size()){
19     cnt += (n/(coe*10))*coe;
20     if(v[idx-1]>1)  cnt += coe;
21     else if(v[idx-1]==1) cnt += (n%coe+1);
22     coe *= 10;
23     idx++;
24   }
25   cout<<cnt;
26   return 0;
27 }

 

 

 

 

转载于:https://www.cnblogs.com/mr-stn/p/9363120.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值