Calculate a+b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).
Input Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −106≤a,b≤106. The numbers are separated by a space.
Output Specification:
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
Sample Input:
-1000000 9
Sample Output:
-999,991
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
comma: 逗号
-
代码
#include<iostream> #include<vector> #include<string> #include<math.h> #include<algorithm> #include<stack> using namespace std; stack<char> st; int main(){ int n,m; cin >> n >> m; **string s = to_string(n + m); //把相加结果转换为字符串** int cnt = 0;//用来计算数字的个数 for(int i = s.length() - 1; i >= 0; i--) { st.push(s[i]); if (isdigit(s[i])) //判断为是数字 { cnt++; } if (cnt != 0 && cnt % 3 == 0 && i != 0 && isdigit(s[i-1])) { st.push(','); } } while(!st.empty()) { cout << st.top(); st.pop(); } return 0; }
-
总结
挺简单一题,关键是把数字转换为字符串,同时记得这个栈里的元素要设为字符类型。