题解 | #人民币转换#

人民币转换

http://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b

痛苦面具了属于是,华为为什么这么喜欢复杂的字符串处理

#include<bits/stdc++.h>
using namespace std;

unordered_map<char, string> h = {
    {'0',"零"}, {'1',"壹"}, {'2',"贰"}, {'3',"叁"}, {'4',"肆"},
    {'5',"伍"}, {'6',"陆"}, {'7',"柒"}, {'8',"捌"}, {'9',"玖"}
};

unordered_map<int, string> u = {
    {0,""},
    {1,"拾"},
    {2,"佰"},
    {3,"仟"},
};

void handler(double n) {
    double decimal = n - int(n);
    string decimalS = to_string(decimal);
    string integer = to_string(int(n));
    int m = integer.size();
    string ans;
    /***整数部分*****************************/
    if (int(n) != 0) {
        int len = min(m, 4);
        for (int i = 0; i < len; ++i) {
            if (integer[m - 1 - i] == '0') {
                if (i == 0) continue;
                else {
                    if (integer[m - i] == '0') continue;
                    else ans = "零" + ans;
                    continue;
                }
            }
            if (i == 1 && integer[m - 1 - i] == '1') ans = "拾" + ans;
            else {
                ans = u[i] + ans;
                ans = h[integer[m - 1 - i]] + ans;
            }
        }
        ans += "元";
        if (m > 4) {
            string temp = integer.substr(0, m - 4);
            int x = temp.size();
            ans = "万" + ans;
            for (int i = 0; i < x; ++i) {
                if (temp[x - 1 - i] == '0') {
                    if (i == 0) continue;
                    else {
                        if (temp[x - i] == '0') continue;
                        else ans = "零" + ans;
                        continue;
                    }
                }
                if (i == 1 && temp[x - 1 - i] == '1') ans = "拾" + ans;
                else {
                    ans = u[i] + ans;
                    ans = h[temp[x - 1 - i]] + ans;
                }
            }
        }
    }
    /***小数部分****************************************/
    if (decimal == 0) cout << "人民币" + ans + "整" << endl;
    else {
        ans += decimalS[2] != '0' ? h[decimalS[2]] + "角" : "";
        ans += decimalS[3] != '0' ? h[decimalS[3]] + "分" : "";
        cout << "人民币" + ans << endl;
    }
}

int main() {
    double n;
    while (cin >> n) handler(n);
}

alt

全部评论

相关推荐

CrazyBucket:我今天下午也做梦在招聘会上面试一家小厂,给自己气笑了
点赞 评论 收藏
分享
孤寡孤寡的牛牛很热情:为什么我2本9硕投了很多,都是简历或者挂,难道那个恶心人的测评真的得认真做吗
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务