1049 Counting Ones (PAT甲级)

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

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

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

#include 

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 
#include 
#include 

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

你可能感兴趣的:(PAT甲级,算法,c++,pat考试)