题解 | #人民币转换#

人民币转换

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

#include <bits/stdc++.h>

using namespace std;

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

// 输入:151121.15
// 输出:人民币拾伍万壹仟壹佰贰拾壹元壹角伍分
void sayPre(string pre, string& res){
    if (pre == "0") return ; // 判断小数点前面是不是空的
    
    for(int i = 0, j = pre.size() - 1; i < pre.size(); i++, j--){
        // i代表的是我们遍历的字符串, j是我们i后面有几个数
        if(pre[i] != '0' && !(pre[i] == '1' && j % 4 == 1)){
            res += m[pre[i] - '0'];
        }
        //转换中文  // if分别对应后面输出的亿万千百十
        if(j != 0 && j >= 8 && j % 8 == 0){
            res += "亿";
        }
        if (j != 0 and j % 4 == 0 and j % 8 != 0)
            pre[i + 1] == '0' ? res += "万零" : res += "万";
        if (j != 0 and j % 4 == 3 and pre[i] != '0')
            pre[i + 1] == '0' && pre[i + 2] != '0' ? res += "仟零" : res += "仟";
        if (j != 0 and j % 4 == 2 and pre[i] != '0')
            pre[i + 1] == '0' && pre[i + 2] != '0' ? res += "佰零" : res += "佰";
        if (j != 0 and j % 4 == 1 and pre[i] != '0')
            res += "拾";
    }
    
    res += "元"; // 最后我们输出元
}

void sayEnd(string end, string& res){
    if (end == "00")
        res += "整";
    else if (end[0] == '0')
        res += m[end[1] - '0'] + "分";
    else if (end[1] == '0')
        res += m[end[0] - '0'] + "角";
    else
        res += m[end[0] - '0'] + "角" + m[end[1] - '0'] + "分";
    // 分类讨论, 讨论我们小数点后两位的所有情况
}

int main(){
    string s = "";
    while(cin >> s){
        string res = "";
        res += "人民币";
        string pre = "", end = "";
        bool xiaoShuDian = false;
        for(char ch : s){
            if(ch == '.'){
                xiaoShuDian = true;
                continue;
            }
            // 这里我们以小数点为分隔, 把小数点前面的存储到了pre里面,
            // 小数点后面的存储到了end里面
            xiaoShuDian ? end += ch : pre += ch;
        }
        
        sayPre(pre, res);
        sayEnd(end, res);
        
        cout << res << endl;
    }
}

华为题库题解 文章被收录于专栏

牛客华为题库的题解

全部评论

相关推荐

谦虚的布莱克选钝角:华为呢,那个很热情的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务