1005 Spell It Right
Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English.
给定一个非负整数N,你的任务是计算N的所有数字的和,并输出总和的每个数字的英文表示。
Input Specification:
Each input file contains one test case. Each case occupies one line which contains an N (≤10^{100}).
每个输入文件包含一个测试用例。每个测试用例占据一行,其中包含一个N(≤10^{100})。
Output Specification:
For each test case, output in one line the digits of the sum in English words. There must be one space between two consecutive words, but no extra space at the end of a line.
对于每个测试用例,在一行中输出总和的数字的英文单词。两个连续单词之间必须有一个空格,但是行末不能有额外的空格。
Sample Input:
12345
Sample Output:
one five
我的思路
这题还是挺简单的
#include<bits/stdc++.h>
using namespace std;
//数字-单词映射表
const string num[10]={"zero","one","two","three","four","five","six","seven","eight","nine"};
int main(){
//使用string作为输入的载体
string str;
cin>>str;
//s-累加值
int s=0;
for(int i=0;i<str.length();i++){
s+=str[i]-'0';
}
//我的计算过程是倒序,结果是正序
//我使用了字符串数组作为倒爷
vector<string> res;
//司空见惯的数字处理
while(s){
int i=s%10;
res.push_back(num[i]);
s/=10;
}
//由于规定输出只有中间存在空格
//我们先打印出一个来
int temp=res.size()-1;
if(temp>=0) cout<<res[temp];
for(int i=res.size()-2;i>=0;i--){
cout<<" "<<res[i];
}
}
第一次提交,拿了17分,一个测试点失败,我们检查一下边界。
经过一次quickcheck,我们发现在输入0的时候
输入
0
输出为空
这应该不符合题目意思。
很明显,问题出在18行,为了偷懒,我没有将if-else条件补全。这可能会为我后面的刷题制造麻烦,需要改正这个坏毛病。
新的代码如下:
#include<bits/stdc++.h>
using namespace std;
//数字-单词映射表
const string num[10]={"zero","one","two","three","four","five","six","seven","eight","nine"};
int main(){
//使用string作为输入的载体
string str;
cin>>str;
//s-累加值
int s=0;
for(int i=0;i<str.length();i++){
s+=str[i]-'0';
}
//我的计算过程是倒序,结果是正序
//我使用了字符串数组作为倒爷
vector<string> res;
//司空见惯的数字处理
while(s){
int i=s%10;
res.push_back(num[i]);
s/=10;
}
//由于规定输出只有中间存在空格
//我们先打印出一个来
int temp=res.size()-1;
if(temp>=0) cout<<res[temp];
******************
//if-else完整性很重要
else cout<<"zero";
******************
for(int i=res.size()-2;i>=0;i--){
cout<<" "<<res[i];
}
}
Solution
#include <iostream>
using namespace std;
int main() {
string a;
cin >> a;
int sum = 0;
for (int i = 0; i < a.length(); i++)
sum += (a[i] - '0');
string s = to_string(sum);
string arr[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
cout << arr[s[0] - '0'];
for (int i = 1; i < s.length(); i++)
cout << " " << arr[s[i] - '0'];
return 0;
}
可见思路大体上是一致的。
它没用我的数字处理操作和stl,而改用int转string天然倒序的性质,简化了我的步骤,可以借鉴学习。
int sum = 12345;
string s = to_string(sum);
for (int i = 0; i < s.length(); i++){
cout<<s[i]<<" ";
}
输出:
1 2 3 4 5
标题:PAT 1005 正确拼写
作者:Departure
地址:https://www.unreachablecity.club/articles/2023/04/19/1681916899586.html
Comments | 0 条评论