甲级PAT 1005 Spell It Right

1005 Spell It Right (20)(20 分)

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.

Input Specification:

Each input file contains one test case. Each case occupies one line which contains an 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

 题目要求:

计算输入非负整数的每位数之和。并将结果的每位数字转化为英文。最后一位后不能有空格。

解题思路:

由于这里N的范围小于10的100次方,因此没法用long long int存储,只能用字符串处理。字符串对应的每位类型为char。计算每位之和需要将char转化为int型,sum = sum + int(s[i]) – int(‘0’),将char转化为Int结果是对应的ASCII码,所以需要减去0对应的ASCII码。计算和sum后转化为字符串,按字符替换成英文即可。

完整代码:

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

string trans(char c){
	if(c=='0') return "zero";
	else if(c=='1') return "one";
	else if(c=='2') return "two";
	else if(c=='3') return "three";
	else if(c=='4') return "four";
	else if(c=='5') return "five";
	else if(c=='6') return "six";
	else if(c=='7') return "seven";
	else if(c=='8') return "eight";
	else if(c=='9') return "nine";
}

int main(){
	string s,sums,result;
	int i,sum=0;
	stringstream ss;
	cin>>s;
	for(i=0;i<s.length();i++){
		sum = sum + int(s[i]) - int('0');
	}
	ss << sum;
	ss >> sums;
	for(i=0;i<sums.length();i++){
		if(i<sums.length()-1){
			cout<<trans(sums[i])<<" ";
		}else{
			cout<<trans(sums[i]);
		}
	} 
	return 0;
} 

 

点赞