pat训练题--1005 Spell It Right(20 分)

版权声明:未经过本人同意不得转发 https://blog.csdn.net/weixin_42956785/article/details/84675527

1005 Spell It Right (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,你的任务是计算所有数字的总和N,用英语输出总和的每一位数。

输入规格:
每个输入文件包含一个测试用例。每个案例占一行包含一个N(≤10
​100).

输出规格:
对于每个测试用例,在一行中输出英文单词中总和的数字。两个连续的单词之间必须有一个空格,但在一行的末尾没有多余的空格。

样本输入:
12345
样本输出:
one five

本题的考点就再于去怎么处理这么大的数据相加,如果直接相加的话,long型也会溢出

#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
void print(int i)
{
	switch (i)
	{
	case 0:printf("zero"); break;
	case 1:printf("one"); break;
	case 2:printf("two"); break;
	case 3:printf("three"); break;
	case 4:printf("four"); break;
	case 5:printf("five"); break;
	case 6:printf("six"); break;
	case 7:printf("seven"); break;
	case 8:printf("eight"); break;
	case 9:printf("nine"); break;
	}
}
int main()
{
	char ch;
	vector<int>sum;
	sum.push_back(0);
	while ((ch = getchar()) != '\n')
	{
		sum[0] += ch - '0';
		//==========================================核心算法
		if (sum[0] >= 10)
		{
			int k = 0;
			for (int i = 0; i < sum.size()-1; i++)
			{
					sum[i + 1] += sum[i] /10;  //大数据加法实现
					sum[i] = sum[i] % 10;
			}
			if (sum[sum.size() - 1] >= 10)
			{
				sum.push_back(sum[sum.size() - 1] / 10);
				sum[sum.size() - 2] = sum[sum.size() - 2] % 10;
			}
		}
		//===================================================
	}
	bool flag = false;
	for (int i = sum.size() - 1; i >= 0; i--)
	{
		if (flag) {
			printf(" ");
		}
		flag = true;
		print(sum[i]);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42956785/article/details/84675527