PAT 甲 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.
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范围过大,所以用string存储,然后遍历字符串,每一位相加求和,在初始化一个字符数组,依次存储0-9的英文,这样当前数字可以和数组下标对应起来,
字符型数字转整数型数字:n[i]-‘0’
C++代码:

#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
int main(){
	int sum=0;
	string n;
	cin>>n;
	for(int i=0;i<n.length();i++){
		sum=sum+n[i]-'0';
	}
	string s=to_string(sum);
	string arr[10]={"zero","one","two","three","four","five","six","seven","eight","nine"};
	for(int i=0;i<s.length();i++){
		cout<<arr[s[i]-'0'];
		if(i!=s.length()-1){
			cout<<" ";
		}
	}
	return 0;
} 
发布了65 篇原创文章 · 获赞 5 · 访问量 4149

猜你喜欢

转载自blog.csdn.net/u014424618/article/details/105018514