题解 | #人民币转换#很烦这种题

人民币转换

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

#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;

vector<string> table1 =  {"壹", "贰", "叁", "肆", "伍", "陆",
                          "柒", "捌", "玖", "拾"
                         };

vector<string> table2 =  {"角", "分"};
vector<string> table3 =  {"", "拾", "佰", "仟", "", "拾", "佰", "仟", "万"};

int main() {
    string sa, sb, input;
    cin>>input;
    sa = input.substr(0, input.find('.'));
    sb = input.substr(input.find('.')+ 1, input.size() - sa.size() + 1);
    string res = "";
    if (stoi(sb) == 0) {
        res += "元整";
    } else {
        //string sb = to_string(b);
        for (int i = 0; i < sb.size(); i++) {
            if (sb[i] == '0') continue;
            res += table1[sb[i] - '1'] + table2[i];
        }
    }
    if (stoi(sa) != 0) {
        res = "元" + res;
        //string sa = to_string(a);
        int index = 0;
        for (auto iter = sa.rbegin(); iter != sa.rend(); iter++) {
            if (index == 4) res = "万" + res;
            if (*iter == '0') {
                while (*iter == '0') {
                    iter++;
                    index++;
                }
                res = "零" + res;
            }
            if ((index == 1 || index == 5) && *iter == '1') {
                res = "拾" + res;
                continue;
            }

            res = table1[*iter - '1'] + table3[index++] + res;

        }
    }
    cout << "人民币" << res;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务