PAT B1002 写出这个数

读入一个自然数n,计算其各位数字之和,用汉语拼音写出和的每一位数字。

输入格式:每个测试输入包含1个测试用例,即给出自然数n的值。这里保证n小于10100。

输出格式:在一行内输出n的各位数字之和的每一位,拼音数字间有1 空格,但一行中最后一个拼音数字后没有空格。

输入样例: 1234567890987654321123456789

输出样例: yi san wu

#include <stdio.h>
#include <algorithm>
#include <string>
#include <map>
#include <iostream>
#include <stack>
using namespace std;

int main(){
    map<int, string> mp;
    mp[1] = "yi";
    mp[2] = "er";
    mp[3] = "san";
    mp[4] = "si";
    mp[5] = "wu";
    mp[6] = "liu";
    mp[7] = "qi";
    mp[8] = "ba";
    mp[9] = "jiu";
    mp[0] = "ling";
    string s;
    cin >> s;
    int sum = 0;
    for (int i = 0; i < s.length(); i++){
        sum += int(s[i]-'0');
    }
    stack<int> stk;
    while (sum != 0){
        int tmp = sum % 10;
        sum /= 10;
        stk.push(tmp);
    }
    while (!stk.empty()){
        int tmp = stk.top();
        stk.pop();
        if (stk.empty()){
            //printf("%s", mp[tmp]);
            cout << mp[tmp];
        }
        else{
            //printf("%s ", mp[tmp]);
            cout << mp[tmp]<<' ';
        }
    }
    //cout << endl<< mp[0];
    system("pause");
}

注意点:用了stack和map,其实根本不需要,储存0-9的拼音直接用一个string[10]就行了,因为刚好下标是对应的。而题目里10的100次方加和最大是9*100,不会超过3位数,因此也可以不用stack,直接一个int[3]就可以了,用vector也可以,遍历vector用vi.begin,vi.end。

猜你喜欢

转载自www.cnblogs.com/tccbj/p/10359141.html
今日推荐