题解 | #人民币转换#仅供参考

人民币转换

https://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b?tpId=37&tqId=21318&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26pageSize%3D50%26search%3D%25E4%25BA%25BA%25E6%25B0%2591%25E5%25B8%2581%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=%E4%BA%BA%E6%B0%91%E5%B8%81

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    // Write your code here
    let line = await readline()
    let [num1, num2] = line.split(".")
    const strs = num1.replace(/(?=(\d{4})+$)/g, ".").split('.').filter(Boolean)
    // console.log(strs)
    const chars = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖']
    const unit = ['', '拾', '佰', '仟']
    const bigUnit = ['', '万', '亿']

    // 转换四位以下的数字
    function _transform(numStr){
        let result = ''
        for(let i=0; i<numStr.length; i++){
            const digit = +numStr[i]
            const c = chars[digit]
            const u = unit[numStr.length - i - 1]
            // 如果digit为'0',则不加单位
            if(digit===0){
                // 如果result末尾不是'零',才可以加
                if(result[result.length-1] !== chars[0]){
                    result += c
                }
                
            }else{
                result += c+u
            }
        }
        if(result[result.length-1]===chars[0]){
            result = result.slice(0, -1)
        }
        return result
    }
    // _transform('1200')

    let result = '人民币'
    for(let i=0; i<strs.length; i++){
        const part = strs[i]
        const c = _transform(part)
        const u = c ? bigUnit[strs.length - i - 1] : ''
        result += c+u
    }
    // console.log(result)
    if(result !== '人民币'){
        result = (result + '元').replace(/壹拾/g,'拾')
    }
    
    if(num2 === '00'){
        result += '整'
    }else{
        if(num2[0] !== '0'){
            result += chars[num2[0]] + '角'
        }
        if(num2[1] !== '0'){
            result += chars[num2[1]] + '分'
        }
    }
    console.log(result)
})()

全部评论

相关推荐

牛客5655:其他公司的面试(事)吗
点赞 评论 收藏
分享
10-21 23:48
蚌埠坦克学院
csgq:可能没hc了 昨天一面完秒挂
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务