PAT 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 (≤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

题目大意

计算所给数字各位之和,然后用英文输出和的每一位

代码和思路

思路

整体来讲很简单,从高位到低位输出和的每一位,很自然的想到利用stack结构。剩下的就是对输入输出进行处理
输入数N可以直接处理为字符串,也较为方便。
因为题目是非负整数,所以要格外注意零是否在自己的代码中需要进行特殊处理

代码

#include<cstdio>
#include<iostream>
#include<stack>
#include<string>
using namespace std;
stack<int> q;

void Print1(int k) {
	switch (k) {
		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;
		case 0:
			printf(" zero");
			break;
	}
}

void Print2(int k) {
	switch (k) {
	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;
	case 0:
		printf("zero");
		break;
	}
}

int main() {
	string str;
	int sum = 0;
	int temp;
	int i = 0;
	cin >> str;
	i = str.length();
	for (int j = 0; j < i; j++) {
		temp = str[j] - '0';
		sum += temp;
	}
    if(sum == 0){
        printf("zero");
        return 0;
    }
	while (sum != 0) {
		temp = sum % 10;
		sum = sum / 10;
		q.push(temp);
	}
	temp = q.top();
	Print2(temp);
	q.pop();
	while (!q.empty()) {
		temp = q.top();
		Print1(temp);
		q.pop();
	}
	return 0;
}

因为懒得对输出进行特殊处理了。。。所以直接复制了两遍Print函数,不影响效率。
因为使用了栈这样的数据结构,而且直接在代码第98行也就是 temo = q.top() 而且在上面的读入每位的过程中以0为循环边界,所以要对0进行特殊处理。
在对输入的处理中使用了sring然后转化,这里其实还有别的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值