Given a list of monetary amounts in a standard format, please calculate the total amount.
We define the format as follows:
1. The amount starts with '$'.
2. The amount could have a leading '0' if and only if it is less then 1.
3. The amount ends with a decimal point and exactly 2 following digits.
4. The digits to the left of the decimal point are separated into groups of three by commas (a group of one or two digits may appear on the left).
Input
The input consists of multiple tests. The first line of each test contains an integer N (1 <= N <= 10000) which indicates the number of amounts. The next N lines contain N amounts. All amounts and the total amount are between $0.00 and $20,000,000.00, inclusive. N=0 denotes the end of input.
Output
For each input test, output the total amount.
Sample Input
2
$1,234,567.89
$9,876,543.21
3
$0.01
$0.10
$1.00
0
Sample Output
$11,111,111.10
$1.11
一开始没有将字符串中的其他符号去掉,将直接加了,漏掉了很多情况,所以还是应该老老实实的去掉其他符号后做大数加法。
输出的时候再把符号加回去。
1 #include <iostream> 2 #include <string> 3 #include <cstdio> 4 #include <algorithm> 5 #include <vector> 6 using namespace std; 7 8 string add(string s1, string s2){ 9 int flag = 0, sum, i; 10 string s = ""; 11 int len1 = s1.length(), len2 = s2.length(); 12 if(len1 < len2){ 13 swap(s1, s2); 14 } 15 len1 = s1.length(), len2 = s2.length(); 16 reverse(s1.begin(), s1.end()); 17 reverse(s2.begin(), s2.end()); 18 for(i = 0; i < len1 && i < len2; i++){ 19 sum = (int)(s1[i] - '0') + (int)(s2[i] - '0') + flag; 20 s += (char)(sum % 10 + '0'); 21 flag = sum / 10; 22 } 23 while(i < len1){ 24 sum = (int)(s1[i] - '0') + flag; 25 s += (char)(sum % 10 + '0'); 26 flag = sum / 10; 27 i++; 28 } 29 if(flag == 1) 30 s += '1'; 31 reverse(s.begin(), s.end()); 32 return s; 33 } 34 35 int main(){ 36 string s1, s2, str1, str2; 37 char c; 38 int n, i; 39 while(cin >> n){ 40 if(n == 0) 41 break; 42 s1 = ""; 43 while(n--){ 44 cin >> s2; 45 str2 = ""; 46 //去符号 47 int len1 = s1.length(), len2 = s2.length(); 48 for(i = 0; i < len2; i++) 49 if(s2[i] >= '0' && s2[i] <= '9') 50 str2 += s2[i]; 51 s1 = add(s1, str2); 52 } 53 reverse(s1.begin(), s1.end()); 54 int len = s1.length(); 55 string ans = ""; 56 for(int i = 0; i < len; i++){ 57 ans = ans + s1[i]; 58 if(i == 1) 59 ans = ans + '.'; 60 if(i > 2 && (i - 1) % 3 == 0 && i != len - 1) 61 ans = ans + ','; 62 } 63 ans += '$'; 64 reverse(ans.begin(), ans.end()); 65 66 cout << ans << endl; 67 } 68 return 0; 69 }