1005. Spell It Right (20)

来源:互联网 发布:微商与淘宝的本质区别 编辑:程序博客网 时间:2024/05/21 10:57

1005. Spell It Right (20)

Question
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


今天,重新做了这道题目,然后思路和之前的完全不一样。上回是用特别数学的方法来实现的,这次想得很简单,就是一些数据类型的转换就行了。
先用string把input读入,然后每一位转成int并相加,得到总和。然后再把总和转成string,把string拆分,然后每一位转成int,然后用这个int去vector中找对应的数字英文。
代码如下:

#include <iostream>#include <string>#include <sstream>#include <vector>using namespace std;int main(int argc, const char * argv[]) {    vector<string> numbers        = {"zero","one","two","three","four","five","six","seven","eight","nine"};    string number;    cin >> number;    int sum = 0;    stringstream stream;    int digit;    for (int i = 0; i < number.length(); ++i) {        stream << number.at(i);        stream >> digit;        sum += digit;        stream.clear();    }    string sum_str;    stream << sum;    stream >> sum_str;    stream.clear();    for (int i = 0; i < sum_str.length(); ++i) {        stream << sum_str.at(i);        stream >> digit;        stream.clear();        if (i == 0) {            cout << numbers.at(digit);        }else {            cout << " " << numbers.at(digit);        }    }    cout << endl;    return 0;}

之前的做法:
这道题目应该要注意的点:

  1. 要记得考虑输入的为0的情况
  2. 此题中要求输入的数最大可达10^100,这时用long long都不够存,这种情况下,应该使用char[]数组,或者string
#include <iostream>#include <string>#include <vector>using namespace std;int main(int argc, const char * argv[]) {    std::string temp;    cin>>temp;    //求和sum    int sum = 0;    for (int i = 0; i < temp.length(); ++i) {        sum += temp[i] - '0';    }    if (sum == 0) {        cout << "zero" << endl;        return 0;    }    //拆分sum    std::vector<int> digits;    while (sum != 0) {        digits.push_back(sum % 10);        sum = sum / 10;    }    string numbers[10] = {"zero","one","two","three","four","five","six","seven","eight","nine"};    vector<int>::iterator iterator;    for (iterator = digits.end() - 1; iterator != digits.begin() - 1; --iterator) {        if (iterator == digits.end() - 1) {            cout << numbers[*iterator];        } else {            cout << " " << numbers[*iterator];        }    }    cout << endl;    return 0;}
0 0