1001. A+B Format (20)

来源:互联网 发布:gson 源码 编辑:程序博客网 时间:2024/06/06 01:41

1001. A+B Format (20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

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
分析:看到这题感觉简单,就按着思路写程序。刚开始时还没注意到那个逗号(英文不好T_T),起初写的是三个数、三个数的存取,sorry,只通过了几个测试点。接着网查了下,数据应该逐个存取,改过来继续。。。刚接触了vector,感觉很好用,数据存在vector中。
  1. #include<iostream>
  2. #include<cmath>
  3. #include<vector>
  4. using namespace std;
  5. int main()
  6. {
  7. int A,B,sum=0,temp;
  8. vector<int> s;
  9. vector<int>::iterator it;
  10. int flag=0;
  11. //freopen("C:\\Documents and Settings\\Administrator\\桌面\\cin.txt","r",stdin); //数据输入路径,调试程序方便
  12. cin>>A>>B;
  13. sum=A+B;
  14. if(sum==0){
  15. cout<<"0"<<endl;
  16. return 0;
  17. }
  18. if(sum<0)
  19. cout<<"-";
  20. sum=abs(sum);
  21. while(sum!=0){//将sum逐个分开
  22. temp=sum%10;
  23. s.push_back(temp);
  24. sum=sum/10;
  25. }
  26. flag=3-(s.size()%3);//flag,逗号输出标记
  27. for(it=s.end()-1;it!=s.begin();it--){
  28. if(!s.empty()){
  29. cout<<(*it);
  30. flag++;
  31. if(flag%3==0)
  32. cout<<",";
  33. }
  34. }
  35. cout<<(*it)<<endl;
  36. return 0;
  37. }
0 0
原创粉丝点击