1001 A+B Format (20 分)

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 −. 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

 

  

tip:因为这道题仅仅是整形数据相加且相后的数据在long long之内,所以直接先相加,之后转换成字符串类型把逗号加上即可

 

AC:

 1 #include<bits/stdc++.h>
 2 #include<stdlib.h>
 3 using namespace std;
 4 int main()
 5 {
 6     int a,b;
 7     cin>>a>>b;
 8     char s[50];
 9     string ss;
10     sprintf(s,"%d",a+b); //将数值类型转换为string类
11     int k=0;
12     for (int i=strlen(s)-1;i>=0;i--,++k)//从后往前遍历,每3位加一个逗号
13     {
14         if (k==3&&s[i]!='-'){
15             k=0;
16             ss.insert(ss.begin(),',');
17         }
18         ss.insert(ss.begin(),s[i]);
19     }
20     cout<<ss<<endl;
21 }

 

上一篇:Redis技术专题系列之核心数据结构特性介绍和案例分析


下一篇:第一周作业