原创 PAT甲级真题 1049 Counting Ones (30分) C++实现(数学问题,找计算公式)

博客讲述了如何解决PAT甲级编程题1049,该题要求计算从1到N的所有正整数中1的总数。博主分享了思路,即通过将数字转换为字符串,分析每个位置为1时可能的组合,并给出了柳神提供的简洁解法代码片段。
摘要由CSDN通过智能技术生成

题目

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

思路

把数字用string保存,视作a[0]a[2]……a[n-1],考察每一位作为1可以有的数字个数,用M[i]记录。

设第i位为1,把左侧部分a[0]…a[i-1]视为一个数字A1,右侧部分a[i+1]…a[n-1]视作一个数字A2。

若a[i] < 1,M[i] = A1 * 10^(n-i-1)
若a[i] = 1,M[i] = A1 * 10^(n-i-1) + (A2+1)
若a[i] > 1,M[i] = (A1+1) * 10^(n-i-1)

下面考虑两端情况。
对于a[0](首位不能为0):

若a[0]=1,M[0] = A2+1
若a[0]>1,M[0] = 10^(n-1)

可见a[0]可以在A1=0时符合通用情况。

对于a[n-1]:

若a[n-1]<1,M[n-1] = A1
若a[n-1]=1,M[n-1] = A1 + 1
若a[n-1]>1,M[n-1] = A1 + 1

可见a[n-1]可以在A2=0时符合通用情况。

所以若A1或A2不存在就相应赋值为:A1=0,A2=a[n-1],可用以上通用公式求解。

(竟然用了3个小时…智商堪忧…一开始没有把a[i]=1的情况单独考虑,而是直接考虑了a[i]<=1,其实等于0和等于1时是不同的!)


柳神的代码是从最后一位开始计算,简洁了许多:
1049. Counting Ones (30)-PAT甲级真题(数学问题)

代码

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int main(){
    string a;
    cin >> a;

    int sum = 0;
    int n = a.size();
    for (int i=0; i<n; i++){
        int A1 = i>0 ? stoi(a.substr(0, i)) : 0;
        int A2 = i<n-1 ? stoi(a.substr(i+1, n-1-i)) : 0;
        if (a[i]<'1'){
            sum += (A1 * pow(10, n-i-1));
        }
        else if(a[i]=='1'){
            sum += (A1 * pow(10, n-i-1) + A2 + 1);
        }
        else{
            sum += ((A1+1) * pow(10, n-i-1));
        }
    }
    cout << sum << endl;
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值