华为OJ 初级:人民币转换

本文介绍了一种将阿拉伯数字转换为符合中文财务规定的人民币大写金额的方法。通过使用特定的字符数组来映射数字和单位,并通过一系列字符串操作确保转换后的格式正确无误。

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

描述

考试题目和要点:

1、中文大写金额数字前应标明“人民币”字样。中文大写金额数字应用壹、贰、叁、肆、伍、陆、柒、捌、玖、拾、佰、仟、万、亿、元、角、分、零、整等字样填写。(30分) 

2、中文大写金额数字到“元”为止的,在“元”之后,应写“整字,如¥ 532.00应写成“人民币伍佰叁拾贰元整”。在”角“和”分“后面不写”整字。(30分) 

3、阿拉伯数字中间有“0”时,中文大写要写“零”字,阿拉伯数字中间连续有几个“0”时,中文大写金额中间只写一个“零”字,如¥6007.14,应写成“人民币陆仟零柒元壹角肆分“。(

 

知识点 字符串
运行时间限制 10M
内存限制 128
输入

输入一个doulbe数

输出

输出人民币格式

注:

下面乱码为:

人民币拾伍万壹仟壹佰贰拾壹元壹角伍分

 
 人民币拾伍万壹仟壹佰贰拾壹元壹角伍分 
样例输入 151121.15
样例输出 人民币拾伍万壹仟壹佰贰拾壹元壹角伍分
import java.util.Arrays;
import java.util.Scanner;

public class Main{
	public static final char[] chNumSet = "零壹贰叁肆伍陆柒捌玖".toCharArray();
	public static final char[] chPowSet = "分角元拾佰仟万拾佰仟亿拾佰仟万".toCharArray();

	public static void main(String[] args) {
		new Main().go();
	}

	private void go() {
		// 读入一个数值
		Scanner console = new Scanner(System.in);
		while (console.hasNext()) {
			double d = console.nextDouble();
			// 解析该数值为汉字形式
			long l = (long) (d * 100);
			String strRes = parse(l);
			System.out.println("人民币" + strRes);
		}
	}

	private String parse(long n) {
		if (n == 0) {
			return "零元整";
		}

		StringBuilder sb = new StringBuilder();
		// 将数值解析为单个数值的数组
		int[] nums = toNum(n);
		for (int i = nums.length - 1; i >= 0; i--) {
			sb.append(chNumSet[nums[i]]);
			sb.append(chPowSet[i]);
		}

		String res = sb.toString().replaceAll("零[分角拾佰仟]", "零")
				.replaceAll("零+", "零").replaceAll("零+元", "元")
				.replaceAll("零+万", "万").replaceAll("零+亿", "亿")
				.replaceAll("亿万", "亿");
		if (res.startsWith("壹拾")) {
			res = res.substring(1);
		}

		if (res.endsWith("零")) {
			res = res.substring(0, res.length() - 1);
		}

		if (res.endsWith("元")) {
			res = res + "整";
		}
		return res;
	}

	private int[] toNum(long n) {
		int[] res = new int[0];
		while (n != 0) {
			int end = (int) (n % 10L);
			// 扩展数组的长度
			res = Arrays.copyOf(res, res.length + 1);
			res[res.length - 1] = end;
			n /= 10L;
		}
		return res;
	}
}

之前看的别人的解法,我觉得挺巧妙的,找不到原文出处了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值