|
| 1 | +package 其他.阿拉伯数字转中文; |
| 2 | + |
| 3 | +/** |
| 4 | + * @author yuanguangxin |
| 5 | + */ |
| 6 | +public class Main { |
| 7 | + private static final char[] numArrays = {'零', '一', '二', '三', '四', '五', '六', '七', '八', '九'}; |
| 8 | + private static final char[] units = {'十', '百', '千', '万', '亿'}; |
| 9 | + private static final StringBuilder ans = new StringBuilder(); |
| 10 | + |
| 11 | + /** |
| 12 | + * 采用递归的方法将转换的结果存储到 ans 变量中, 注意 `万` 和 `亿` 在 units 数组中不是连续的, 所以 |
| 13 | + * 当数字达到5位数或9位数时, 我们分开讨论。 |
| 14 | + * |
| 15 | + * @param num |
| 16 | + */ |
| 17 | + private static void intToChineseNum(int num) { |
| 18 | + String s = String.valueOf(num); |
| 19 | + char[] chars = s.toCharArray(); |
| 20 | + int n = chars.length; |
| 21 | + |
| 22 | + // 只剩下一位时, 直接返回 numArrays 数组中对应的数字 |
| 23 | + if (n == 1) { |
| 24 | + ans.append(numArrays[chars[0] - '0']); |
| 25 | + // 如果 num 超过 5 位, 则先判断是否上亿, 然后将 num 拆分 |
| 26 | + } else if (n >= 5) { |
| 27 | + n = n >= 9 ? 9 : 5; |
| 28 | + int multi = (int) Math.pow(10, n - 1); |
| 29 | + // div 表示 num 中上亿或上万的部分数值 |
| 30 | + int div = num / multi; |
| 31 | + // mod 表示剩余的部分数值 |
| 32 | + int mod = num % multi; |
| 33 | + // 对前一部分数值进行转换, 然后添加单位万/亿 |
| 34 | + intToChineseNum(div); |
| 35 | + ans.append(n == 5 ? units[3] : units[4]); |
| 36 | + String s1 = String.valueOf(div); |
| 37 | + String s2 = String.valueOf(mod); |
| 38 | + // 判断中间是否有 0 |
| 39 | + if (s.charAt(s1.length() - 1) == '0' || s2.length() < n - 1) ans.append("零"); |
| 40 | + // 转换剩余部分 |
| 41 | + intToChineseNum(mod); |
| 42 | + // 如果 num 不超过 5 位, 处理过程与上面相似 |
| 43 | + } else { |
| 44 | + int multi = (int) Math.pow(10, n - 1); |
| 45 | + int div = num / multi; |
| 46 | + int mod = num % multi; |
| 47 | + ans.append(numArrays[div]).append(units[n - 2]); |
| 48 | + if (mod != 0) { |
| 49 | + if (String.valueOf(mod).length() < n - 1) { |
| 50 | + ans.append("零"); |
| 51 | + } |
| 52 | + intToChineseNum(mod); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + public static void main(String[] args) { |
| 58 | + Main.intToChineseNum(121399013); |
| 59 | + System.out.println(ans.toString()); |
| 60 | + } |
| 61 | +} |
0 commit comments