题解 | #人民币转换#

人民币转换

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String[] val = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };// 0~9
        String[] k1 = { "元", "万", "亿" };// k=1时的单位
        String[] k032 = { "仟", "", "拾", "佰" };// k=0 2 3时的单位
        String[] decimal = { "整", "角", "分" };
        StringBuffer bu = new StringBuffer();
        String prex = "人民币";
        bu.append(prex);
        String a = null;
        try {
            a = in.readLine();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        int l = a.length(), i = 0, j, k, num = 0, zeroNum = 0;
        boolean f1 = true;
        char[] chrInteger = new char[l - 3];
        char[] chrDecimal = new char[3];
        a.getChars(0, l - 3, chrInteger, 0);
        a.getChars(l - 3, l, chrDecimal, 0);
        l -= 3;// 循环遍历只考虑整数位
        while (i < l) {
            num = chrInteger[i] - '0';
            if (num == 0) {
                zeroNum++;
                i++;
                continue;
            }
            if (zeroNum > 0) {// 该位前面有0
                if (l - i != 4)// 该位不是千位,就加0;千前面是0,就不加0
                    bu.append(val[0]);
                zeroNum = 0;// 0的个数重置为0,
            }
            j = (l - i) /
                4;// 该位是4的几倍,0倍就是个位到千位,1倍就是万位到千万位
            k = (l - i) %
                4;// 该位是1~4位的第几位,以4作为循环依据,个,十,百,千
            if (k == 2 &&
                    chrInteger[i] == '1') {// k=2,是十位,且是1,就不用加1,只加十
                bu.append(k032[2]);
            } else if (k ==
                       1) {// k=2,是个位,看是j的值,如j=0对应元,j=1对应万,j=2对应亿
                bu.append(val[num]).append(k1[j]);
            } else {// 其他位,k=2,k=3,k=0,对应十,百,千
                bu.append(val[num]).append(k032[k]);
            }
            i++;
        }
        getDecimal(bu, decimal, val, chrDecimal);// 获得小数位
        System.out.print(bu);
    }

    public static void getDecimal(StringBuffer bu, String[] decimal,
                                  String[] val, char[] chrDecimal) {
        int i1 = chrDecimal[1] - '0', i2 = chrDecimal[2] - '0';
        if (i1 == 0 && i2 == 0) {
            bu.append(decimal[0]);
        } else if (i2 == 0) {
            bu.append(val[i1]).append(decimal[1]);
        } else if (i1 == 0) {
            bu.append(val[i2]).append(decimal[2]);
        } else {
            bu.append(val[i1]).append(decimal[1]).append(val[i2]).append(
                decimal[2]);
        }
    }
}

全部评论

相关推荐

被子有点短:有了实习后会发现有实习也没用
投递字节跳动等公司10个岗位
点赞 评论 收藏
分享
Java面试先知:我也是和你一样的情况,hr 说等开奖就行了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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