【PAT】1005 Spell It Right

题目:http://pat.zju.edu.cn/contests/pat-a-practise/1005

分析:简单题。将输入的字符串一个个的转换成数字再相加,然后将相加的结果用英文打印出来就可以。输入输出的顺序需要用到栈的知识。

题目描述:

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 (<= 10100).

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<iostream>
#include<string.h>
#include<string>
#include<stack>
using namespace std;
#define max 102
char input[max];
int main()
{
	cin>>input;
	int len;
	int sum=0,i,temp;
	stack<string> result;
	len = strlen(input);
	for(i=0; i<len; i++)
		sum += input[i] - '0';	

	do
	{
		temp = sum%10;
		if(temp == 0) result.push("zero");
		else if(temp == 1) result.push("one");
		else if(temp == 2) result.push("two");
		else if(temp == 3) result.push("three");
		else if(temp == 4) result.push("four");
		else if(temp == 5) result.push("five");
		else if(temp == 6) result.push("six");
		else if(temp == 7) result.push("seven");
		else if(temp == 8) result.push("eight");
		else if(temp == 9) result.push("nine");
        sum /= 10;
	}while(sum != 0);

	cout<<result.top();
	result.pop();
	while(!result.empty())
	{
		cout<<" "<<result.top();
		result.pop();
	}
	cout<<endl;
	return 0;
}

也可以用switch case来处理。

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

string process(int a){
	switch(a){
	case 0:
		return "zero";
	case 1:
		return "one";
	case 2:
		return "two";
	case 3:
		return "three";
	case 4:
		return "four";
	case 5:
		return "five";
	case 6:
		return "six";
	case 7:
		return "seven";
	case 8:
		return "eight";
	case 9:
		return "nine";
	}
}

int main(){
	string str;
	cin>>str;
	long result = 0;
	int i ;
	for(i=0; i<str.size(); i++){
		result += str[i] - '0';
	}
	if(result == 0){
		cout<<"zero"<<endl;
		return 0;
	}
	stack<string> sta;
	while(result != 0){
		sta.push(process(result%10));
		result /= 10;
	}
	cout<<sta.top();
	sta.pop();
	while(!sta.empty()){
		cout<<" "<<sta.top();
		sta.pop();
	}
	cout<<endl;
	return 0;
}


你可能感兴趣的:(pat,cc++)