TopCoder 250 points 12-SRM 149 DIV 2 103.92/250 41.57%

Problem Statement

 In documents, it is frequently necessary to write monetary amounts in a standard format. We have decided to format amounts as follows:
  1. the amount must start with '$'
  2. the amount should have a leading '0' if and only if it is less then 1 dollar.
  3. the amount must end with a decimal point and exactly 2 following digits.
  4. the digits to the left of the decimal point must be separated into groups of three by commas (a group of one or two digits may appear on the left).

Create a class FormatAmt that contains a method amount that takes two int's, dollars and cents, as inputs and returns the properly formatted String.

Definition

 
Class:FormatAmt
Method:amount
Parameters:int, int
Returns:String
Method signature:String amount(int dollars, int cents)
(be sure your method is public)
 
 

Notes

-One dollar is equal to 100 cents.

Constraints

-dollars will be between 0 and 2,000,000,000 inclusive
-cents will be between 0 and 99 inclusive

Examples

0) 
 
123456
0
Returns: "$123,456.00"
Note that there is no space between the $ and the first digit.
1) 
 
49734321
9
Returns: "$49,734,321.09"
 
2) 
 
0
99
Returns: "$0.99"
Note the leading 0.
3) 
 
249
30
Returns: "$249.30"
 
4) 
 
1000
1
Returns: "$1,000.01"
 

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.     

写了个很土的办法,,别人有两行就搞定的,要提高基本功啊

public class FormatAmt {

	public static String amount(int dollars, int cents) {
		int numOfComma = 0;
		String s1 = dollars + "";
		int len1 = s1.length(), lenA = len1;
		String s2 = cents + "";
		int len2 = s2.length();
		boolean canBeDivided = false;
		if (len1 % 3 == 0) {
			canBeDivided = true;
		}
		int l = len1 / 3;
		if (len1 > 3) {
			numOfComma = canBeDivided ? l - 1 : l;
		}
		StringBuilder sb = new StringBuilder();
		sb.append("$");
		if (numOfComma > 0) {
			char a[] = s1.toCharArray();
			char b[] = new char[len1 + numOfComma];
			int temBlen = b.length;
			for (int j = 0, i = temBlen - 1; i >= 0; i--)
				if (j == 3) {
					b[i] = ',';
					j = 0;
				} else {
					b[i] = a[--lenA];
					j++;
				}
			for (int i = 0; i < b.length; i++)
				sb.append(b[i]);
		} else {
			sb.append(s1);
		}

		sb.append(".");
		if (len2 == 2)
			sb.append(s2);
		else
			sb.append("0").append(s2);
		return sb.toString();

	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值