看到一题华为面试题,数字转成人民币,写了个方法.

本文介绍了一个将阿拉伯数字转换为中文人民币金额的Java方法实现。该方法考虑了特殊字符的处理和性能优化,避免使用字符串替换等操作以提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看到一题华为面试题,数字转成人民币,写了个方法.如: 12345转为一万二千三百四十五元.

1.注意特殊字符的处理

2.性能.  少用string的replace等方法,这种方法没有index,遍历string很费性能,应在一个循环中做,而不是多次循环.


public class NumberToMenoy {
 public static void main(String[] args) {
  NumberToMenoy t = new NumberToMenoy();
  long t1 = System.currentTimeMillis();
  String[] num = new String[5];
  num[0] = "1234567890";
  num[1] = "1000000000";
  num[2] = "1000500022";
  num[3] = "1000000000000000000";
  num[4] = "10000000000000";
  for(int j =0;j<10000;j++){
   for (int i = 0; i < num.length; i++) {
    t.conversion(num[i]);
   }
  }
  long t2 = System.currentTimeMillis() - t1 ;
  System.out.println("运算时间:"+t2);
 }

 public void conversion(String money){
  String[] cn = {"零","一","二","三","四","五","六","七","八","九"};
  String[] unit = {"十","百","千"};
  StringBuffer cnMoney = new StringBuffer();
  int m ;
  int b = 0;
  int le = money.length();
  for(int i = 0;i<le;i++){
   m = Integer.parseInt( money.substring(i,i+1) );
   b += m ;
   if( !(m == 0 && cnMoney.charAt(cnMoney.length()-1) == '零') ){
    cnMoney.append(cn[m]);
   }
   int j = (money.length()-i-1) % 4 ;
    if( j == 0 ){
     if (cnMoney.charAt(cnMoney.length() - 1) == '零') {
      cnMoney.deleteCharAt(cnMoney.length() - 1);
     }
     if( (money.length()-i-1)/4%2==0){
      cnMoney.append("亿");
     }else{
      if(b != 0){
       cnMoney.append("万");
      }
     }
     b = 0 ;
    }else{
     if(m != 0){
      cnMoney.append(unit[j-1]);
     }
    }
  }
  if(cnMoney.charAt(0)=='一' && cnMoney.charAt(1)=='十'){
   cnMoney.deleteCharAt(0);
  }
  cnMoney.replace(cnMoney.length()-1, cnMoney.length(), "元");
  //System.out.println(money+"    "+cnMoney);
 }
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值