题解 | #阿拉伯数字转中文#
阿拉伯数字转中文
https://www.nowcoder.com/practice/6eec992558164276a51d86d71678b300
public static String nextGreaterElement(long n) { Map<Integer, String> num2Chn = new HashMap<>(); num2Chn.put(0, "零"); num2Chn.put(1, "一"); num2Chn.put(2,"二"); num2Chn.put(3,"三"); num2Chn.put(4, "四"); num2Chn.put(5,"五"); num2Chn.put(6,"六"); num2Chn.put(7,"七"); num2Chn.put(8,"八"); num2Chn.put(9,"九"); num2Chn.put(10,"十"); num2Chn.put(100,"百"); num2Chn.put(1000,"千"); if(n==0) return num2Chn.get(0); StringBuilder sb = new StringBuilder(); Stack<String> stack = new Stack<>(); int i = 1; long pre = -1; while(n>0){ int t = (int) (n%10); n /=10; if(t>0 || (t == 0 && pre != 0 && i>1)) { String s = num2Chn.get(t); if(i%4 == 2 && t>0){ sb.append(num2Chn.get(10)); }else if(i%4==3&& t>0){ sb.append(num2Chn.get(100)); }else if(i%4 == 0&& t>0){ sb.append(num2Chn.get(1000)); } sb.append(s); } pre = t; i++; if(i == 5 || i == 9 || n<=0){ sb.reverse(); String s = sb.toString(); if(s.startsWith("一十")) s = s.substring(1); stack.push(s); i = 1; pre = -1; sb = new StringBuilder(); } } StringBuilder res = new StringBuilder(); while(!stack.isEmpty()){ res.append(stack.pop()); if(stack.size() == 2){ res.append("亿"); }else if(stack.size() == 1 && res.charAt(res.length()-1) != '亿'){ res.append("万"); } } return res.toString(); }
每四个数字一组,分别处理,因为 个十百千/ 万 十万 百万 千万/ 亿 十亿 百亿 千亿 都是四个数字一组
这篇文章的思路很好可以看下,我的思路也借鉴这里
https://juejin.cn/post/7056769354452434975
测试用例也借鉴了这篇博客
System.out.println(Solution.cal(0)); System.out.println(Solution.cal(1)); System.out.println(Solution.cal(10)); System.out.println(Solution.cal(15)); System.out.println(Solution.cal(25)); System.out.println(Solution.cal(100)); System.out.println(Solution.cal(115)); System.out.println(Solution.cal(234)); System.out.println(Solution.cal(999)); System.out.println(Solution.cal(1501)); System.out.println(Solution.cal(1006)); System.out.println(Solution.cal(9905)); System.out.println(Solution.cal(20394)); System.out.println(Solution.cal(100001)); System.out.println(Solution.cal(100000)); System.out.println(Solution.cal(100101822)); System.out.println(Solution.cal(123412341234L)); System.out.println(Solution.cal(10000000000L)); 零 一 十 十五 二十五 一百 一百一十五 二百三十四 九百九十九 一千五百零一 一千零六 九千九百零五 二万零三百九十四 十万零一 十万 一亿零一十万一千八百二十二 一千二百三十四亿一千二百三十四万一千二百三十四 一百亿