TopCoder 250 points 12-SRM 149 DIV 2 103.92/250 41.57%
2013-05-31 21:15
519 查看
Problem Statement | ||||||||||||
In documents, it is frequently necessary to write monetary amounts in a standard format. We have decided to format amounts as follows: the amount must start with '$' the amount should have a leading '0' if and only if it is less then 1 dollar. the amount must end with a decimal point and exactly 2 following digits. 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 | ||||||||||||
| ||||||||||||
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) | ||||||||||||
| ||||||||||||
1) | ||||||||||||
| ||||||||||||
2) | ||||||||||||
| ||||||||||||
3) | ||||||||||||
| ||||||||||||
4) | ||||||||||||
|
写了个很土的办法,,别人有两行就搞定的,要提高基本功啊
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(); } }
相关文章推荐
- TopCoder 250 points 11-SRM 149 DIV 1 86.62/250 34.65%
- Topcoder SRM 661 (Div.1) 250 MissingLCM - 数论
- TopCoder 250 points 13-SRM 150 DIV 1 82.63/250 33.05%
- TopCoder 250 points 18-SRM 152 DIV 2 167.05/250 66.82%
- TopCoder 250 points 19-SRM 153 DIV 1 84.72/250 33.89%
- TopCoder SRM 596 DIV 1 250
- TopCoder 250 points 28-SRM 157 DIV 2 185.60/250 74.24%
- 【topcoder SRM 652 DIV2 250】ValueOfString
- TopCoder 250 points 3-SRM 145 DIV 1 84.71/250 33.88%
- TopCoder 250 points 20-SRM 153 DIV 2 216.58/250 86.63%
- TopCoder_SRM_144_DIV2_250_Time
- Topcoder SRM 641 Div1 250(另辟蹊径,排除法)
- TopCoder 250 points 4-SRM 145 DIV 2 128.72/250 51.49%
- 小朋友学TopCoder(7):SRM726 DIV2 250-point
- topcoder SRM 543 div2 250
- topcoder SRM 541 div2 250
- 【topcoder SRM 702 DIV 2 250】TestTaking
- TopCoder 250 points 6-SRM 146 DIV 2 162.67/250 65.07%
- TopCoder 250 points 9-SRM 148 DIV 1 75/250 30%
- topcoder SRM 548 DIV2 250