PAT甲级1049 Counting Ones (30分)|C++实现

一、题目描述

原题链接
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( N ≤ 2 30 N\leq2^{30} N230).

​​Output Specification:

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

Sample Input:

12

Sample Output:

5

二、解题思路

看到这道题目,我们第一想法可能是从1到N遍历,对于每个数去计算1的个数,但是这样计算,时间复杂度较高,会有测试点超时,所以我们要寻找一下别的解法。接下来的解法取自《编程之美》P132。

事实上,给定了N,我们可以通过分析“小于N的数在每一位上可能出现1的次数”之和来得到这个结果。显然,对于一个个位数N,如果 N ≥ 1 N\geq1 N1 f ( N ) = 1 f(N) = 1 f(N)=1。对于2位数,假设 N = 13 N=13 N=13,不难发现,个位出现1的数字有两个,1和11,十位出现1的数字有四个,10、11、12和13。由于11有两个1,我们正常加起来时将11这个数计算了两次,所以不用特殊处理。

接下来我们推导一般情况下,从N得到f(N)的计算方法。假设 N = a b c d e N = abcde N=abcde,如果要计算百位上出现1的次数,要考虑三个因素:百位的数字,百位以下的数字,百位以上的数字。如12013,百位出现1的情况:100199,1100~1199,2100~2199,3100~3199…,1110011199,共有1200个,即由更高位数字决定,并且等于更高位数 × \times ×当前位数。若百位数字为1,则1200还要加上12100~12113共114个。当百位数字大于1时,则原来1200个还要加上12100~12199这100个,共1300个,即等于更高位数字+1再乘以当前位数。对于其他各数位都是如此,写出代码如下。

这个算法是真的非常巧妙,我这里只做了简述,建议去找原书进行阅读,真的会有一种醍醐灌顶的感觉。

三、AC代码

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
    
    
  int N, cnt = 0, a = 1;
  scanf("%d", &N);
  while(N/a)
  {
    
    
    int now = (N/a)%10, left = N/a/10, right = N%a;
    if(now == 0)	cnt += left*a;
    else if(now == 1)	cnt += left*a + right + 1;
   	else	cnt += (left+1)*a;
    a *= 10;
  }
  printf("%d", cnt);
  return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/108595451