1005. Spell It Right (20)解题思路

来源:互联网 发布:mac充电指示灯不亮了 编辑:程序博客网 时间:2024/05/28 05:13

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



思路:

每读入一个字符,就拿该字符与‘0’相减,然后与sum加和。读取完毕之后,如果sum等于0,则直接将sum压入栈;如果sum大于0,则对sum进行循环除十取模,将模存储于堆栈中。然后把0-9十个英文单词存储于一个数组之中,最后每从堆栈中弹出一个模,就输出一个对应的英文单词。

复杂度:

时间复杂度为O(n)。空间复杂度为O(1)。


#include <iostream>#include <vector>#include <cstdio>int main(void){setvbuf(stdin, new char[1 << 20], _IOFBF, 1 << 20);setvbuf(stdout, new char[1 << 20], _IOFBF, 1 << 20);int sum = 0;std::vector<int> stack;char temp;while ((temp = getchar()) != '\n' && temp != EOF) {sum += temp - '0';}if (!sum) {stack.push_back(sum);}while (sum > 0) {stack.push_back(sum % 10);sum /= 10;}const char *string[10] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };printf("%s", string[stack[stack.size() - 1]]);stack.pop_back();while (!stack.empty()) {printf(" %s", string[stack[stack.size() - 1]]);stack.pop_back();}return 0;}


0 0
原创粉丝点击