1049 Counting Ones (PAT甲级)

文章讲述了在解决PAT甲级编程竞赛中的数论问题——CountingOnes时,作者对比了两种不同的解法,一种使用了字符串操作,而另一种则采用了数学逻辑,后者代码更简洁。作者通过重写代码,展示了如何避免使用string来降低代码复杂性,从而提高效率。
摘要由CSDN通过智能技术生成

我和柳婼的基本思路是一致的,但我用了string导致代码复杂了很多……柳婼的解法简洁许多。

1049. Counting Ones (30)-PAT甲级真题(数学问题)_1049 count 柳婼_柳婼的博客-CSDN博客

我按照她的解法重写的代码如下:

#include <cstdio>

int N, sum, a, curr, before, after;

int main(){
    scanf("%d", &N);
    a = 1;
    sum = 0;
    while(N / a != 0){
        curr = N / a % 10;
        before = N / a / 10;
        after = N % a;
        if(curr == 0){
            sum += before * a;
        } else if(curr == 1){
            sum += before * a + after + 1;
        } else{
            sum += (before + 1) * a;
        }
        a *= 10;
    }
    printf("%d", sum);
    return 0;
}

原来的代码如下:

#include <cmath>
#include <string>
#include <iostream>

int sum, sz;
std::string s;

int main(){
    std::cin >> s;
    sum = 0;
    sz = s.size();
    for(int i = 0; i < sz; ++i){
        if(i == 0){
            if(s[i] == '1'){
                if(sz == 1){
                    sum += 1;
                } else{
                    sum += 1 + std::stoi(s.substr(1));
                }
            } else{
                sum += pow(10, sz - 1);
            }
        } else if(i == sz - 1){
            if(s[i] == '0'){
                sum += std::stoi(s.substr(0, sz - 1));
            } else{
                sum += std::stoi(s.substr(0, sz - 1)) + 1;
            }
        } else{
            if(s[i] == '0'){
                sum += std::stoi(s.substr(0, i)) * pow(10, sz - i - 1);
            } else if(s[i] == '1'){
                sum += std::stoi(s.substr(0, i)) * pow(10, sz - i - 1) + std::stoi(s.substr(i + 1)) + 1;
            } else{
                sum += (std::stoi(s.substr(0, i)) + 1) * pow(10, sz - i - 1);
            }
        }
    }
    std::cout << sum;
    return 0;
}

题目如下:

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值