题解 | #人民币转换#
人民币转换
https://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); HashMap<Character, String> map = new HashMap<Character, String>(); map.put('0', "零"); map.put('1', "壹"); map.put('2', "贰"); map.put('3', "叁"); map.put('4', "肆"); map.put('5', "伍"); map.put('6', "陆"); map.put('7', "柒"); map.put('8', "捌"); map.put('9', "玖"); String[] dh = new String[9]; dh[0] = "元"; dh[1] = "拾"; dh[2] = "佰"; dh[3] = "仟"; dh[4] = "万";
dh[5] = "拾"; dh[6] = "佰"; dh[7] = "仟"; dh[8] = "亿"; // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextDouble()) { // 注意 while 处理多个 case double num = in.nextDouble(); String s = "" + num; String[] arr = s.split("\\."); String res = ""; //先看.前面 int j = 0; for (int i = arr[0].length() - 1; i >= 0; i--) { if (arr[0].charAt(i) == '0') { res = map.get('0') + res; j++; } else { res = map.get(arr[0].charAt(i)) + dh[j++] + res; } } //一和十只保留10 for(int i=0; i<res.length(); i++){ if((""+res.charAt(i)).equals("壹") && i+1<res.length() && (""+res.charAt(i+1)).equals("拾")){ res = res.substring(0, i) + res.substring(i+1, res.length()); } } String fin = "人民币"; //去掉多个连续零 for (int i = 0; i < res.length(); i++) { if (("" + res.charAt(i)).equals("零")) { while (i < res.length() && ("" + res.charAt(i)).equals("零")) { i++; } if (i != res.length()) { fin = fin + "零"; i = i - 1; } } else { fin = fin + res.charAt(i); } } String postD[] = new String[2]; postD[0] = "角"; postD[1] = "分"; //看后面 if(arr[1].charAt(0)=='0' && arr[1].charAt(1)=='0'){ fin = fin + "整"; }else{ for(int i=0; i<arr[1].length(); i++){ if(arr[1].charAt(i)!='0') fin = fin + map.get(arr[1].charAt(i)) + postD[i]; } } System.out.println(fin); } }
}