金额转换

题意描述:将阿拉伯数字的金额转换成中国文字描述的金额,如

 

(¥1011 )-> (一千零一拾一元)输出

 

解题思路:“0-9”阿拉伯数字对应的中文文字分别为“'零','壹','贰','叁','肆','伍','陆','柒','捌','玖'”;中文描述金额时会有单位描述,如个位后面带“元”、十位后面带“拾”等等,并且有这样一个规律:个、十、百、千、万、十万、百万、千万、亿,所以分别将对应单位存放在数组中,然后依次取出:

public class MoneyConvert {	
	private static final char[] data = new char[]{
			'零','壹','贰','叁','肆','伍','陆','柒','捌','玖'
	};
	
	private static final char[] units = new char[]{
			'元','拾','佰','仟','万','拾','佰','仟','亿'
	};
	
	private static String convert(int money) {
		StringBuffer str = new StringBuffer();
		int unit = 0;
		while(money != 0){
			str.insert(0, units[unit++]);
			int number = money%10;
			str.insert(0, data[number]);
			money /= 10;
		}
		return str.toString();
	}
	
	public static void main(String[] args) {
		System.out.println(convert(135689123));
               //壹亿叁仟伍佰陆拾捌万玖仟壹佰贰拾叁元
	}
}

C++写法

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string num[] = {"O", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
    string units[] = {"", "十", "百", "千", "万", "十", "百"};

    int money = 9876542;
    cout<<"money:"<<money<<endl;

    int idxUnits = 0;
    string res;
    while (money != 0) {
        res = units[idxUnits++] + res;
        int n = money % 10;
        res = num[n] + res;
        money = money / 10;
    }

    cout<<"chinese:"<<res<<endl;

    return 0;
}

golang写法

package main

import (
    "fmt"
)

func main() {
    num := []string{"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}
    units := []string{"", "拾", "佰", "仟", "万", "拾", "佰"}

    money := 9876543
    fmt.Println("money:", money)

    fmt.Println("chinese:", convert(money, num, units))
}

func convert(money int, num, units []string) (res string) {
    for idxUnits := 0; money != 0; idxUnits++ {
        res = units[idxUnits] + res
        idxNum := money % 10
        res = num[idxNum] + res
        money /= 10
    }
    return
}

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值