我和柳婼的基本思路是一致的,但我用了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
文章讲述了在解决PAT甲级编程竞赛中的数论问题——CountingOnes时,作者对比了两种不同的解法,一种使用了字符串操作,而另一种则采用了数学逻辑,后者代码更简洁。作者通过重写代码,展示了如何避免使用string来降低代码复杂性,从而提高效率。
&spm=1001.2101.3001.5002&articleId=131792746&d=1&t=3&u=c130a413bb224002bcebee7bf23e3b00)
789

被折叠的 条评论
为什么被折叠?



