参考 算法的乐趣
阿拉伯数字 转 汉字大写 如 123 > 壹佰贰拾叁
思路:
如:a = 123,1234,1200
按权位分为 {"","拾","佰","仟"},
按节权位分{"","万","亿","万亿"}
1.将 a 按4位分隔,循环每个分隔,通过位移确定权位,进行转换中文。
然后确定每个分隔后的节权位。
注意对0的转换:
1.10000 不取零
2.1001 取一个零
3.01不取零
如下:
1 package algo; 2 3 public class NumToCh { 4 static String [] chnChar = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"}; 5 //权位 6 static String [] chnUnit = {"","拾","佰","仟"}; 7 //节权位 8 static String [] chnUnitSec = {"","万","亿","万亿"}; 9 10 public static void main(String[] args) { 11 String a = "11120"; 12 String b = "0011120";//001,1120 13 String c = "111002";// 11,1002 14 String d = "11102"; 15 System.out.println(numberTochn(a)); 16 System.out.println(numberTochn(b)); 17 System.out.println(numberTochn(c)); 18 System.out.println(numberTochn(d)); 19 20 } 21 22 private static String numberTochn(String numScan){ 23 int num = Integer.parseInt(numScan); 24 StringBuffer chn = new StringBuffer(); 25 int unitPos = 0; 26 boolean zero = true; 27 while(num>0){ 28 int section = num%10000; 29 if(!zero){ 30 chn.insert(0, chnChar[0]); 31 } 32 //将section转中文 33 String ch = numberToChar(section); 34 //加 节权位 35 if(section!=0){ 36 ch += (chnUnitSec[unitPos]); 37 } 38 chn.insert(0, ch); 39 //千字节为0,需要在下一个 section补零 40 if(section<1000&§ion>0){ 41 zero = false; 42 } 43 //节权位对应的下标 44 unitPos++; 45 //移位下一个 46 num = num/10000; 47 } 48 49 return chn.toString(); 50 } 51 //将数字转换为中文 52 private static String numberToChar(int section) { 53 StringBuffer chn = new StringBuffer(); 54 boolean zero = true; 55 int unitPos = 0 ; 56 while(section>0){ 57 int v = section%10; 58 if(v==0){ 59 //zero控制零(必须判断有数字后,才输入零(01),并且多个连续的0只取一个(0000)) 60 if(!zero){ 61 zero = true; 62 chn.insert(0, chnChar[v]); 63 } 64 }else{ 65 zero = false; 66 String s = chnChar[v] + //转字符 67 chnUnit[unitPos];//权位 68 chn.insert(0,s); 69 } 70 //移位下标 71 unitPos++; 72 //移位下个 73 section = section/10; 74 } 75 return chn.toString(); 76 77 } 78 79 80 }
时间: 2024-10-29 19:10:59