题意描述:将阿拉伯数字的金额转换成中国文字描述的金额,如
(¥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
}