【题意】
输入两个整数,并计算两数的相加和,注意输出时从低位到高位,每隔三位加入一个逗号分隔符,若不满四位则不需要加。
如:123→123,2133→2,133,222333→222,333,-1234567→-1,234,567
【原题链接】
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
【题解】
有两种思路,一种是打印输出的时候间隔输出逗号;另一种是在计算结果字符串内加入分隔逗号,再输出。
(需要注意负号的处理、开头和结尾逗号的处理)
思路一:打印输出时添加逗号分隔符
解法1:cpp利用STL-string的直接遍历处理方式:
难点:插入间隔位的判别处理,总字符数对3取余的余数(即开头的数位情况),直接影响后续的判别下标(在此基础上累加3个单位,然后末尾情况要排除)。
#include <iostream>
#include <cstring>
using namespace std;
int main(){
int a,b,sum;
cin>>a>>b;
sum=a+b;
if(sum!=0){
if(sum<0) cout<<'-';
sum=abs(sum); //负数情况处理
string str=to_string(sum); //转为string类型,进行字符串内部遍历
for(int i=0;i<str.size();i++){ //注意下标从0开始
cout<<str[i];
if(i!=str.size()-1&&(i+1)%3==str.size()%3) //防止尾部多余逗号;遍历序号取余,来判别间隔插入逗号,插入序号为字符总数余数及 每加入三位的所有间隔;
cout<<',';
}
}else //0的情况处理
cout<<'0';
return 0;
}
解法2:cpp内直接用int数组存 逆序数位 来反向遍历处理:
说明:在逆序存储情况下,数组内从左到右 正好是原数从低位到高位每隔三位 插入逗号的下标序列,只要逆序遍历输出,依据下标是否为3的间隔数 即可判别插入逗号,而数组内的末尾 也就是原数的首位同样要进行排除。
#include <iostream>
using namespace std;
int main(){
int a,b,c;
cin>>a>>b;
c=a+b;
if(c!=0){
if(c<0)
cout<<'-';
c=abs(c);
int store[11],i=0;
while(c){
store[i++]=c%10; //将结果通过取余个位,逆序读入进数组(正序读入的话编码上不好拆分数位)
c/=10;
}
i--; //最后一次多余的i++减回去
for(int j=i;j>=0;j--){ //逆序遍历数组,逆逆得正~
if((j+1)%3==0&&j!=i) //数组内逆序情况下,每隔三位下标(逆序)输出间隔逗号;开头情况排除
cout<<',';
cout<<store[j];
}
}
else
cout<<'0';
return 0;
}
思路二:在计算结果字符串内加入分隔逗号,再输出
解法3:用一个string来存结果,逐字向内添加数字和逗号分隔符:
说明:从低位到高位每隔三位数字,添加逗号分隔符,排除高位的首位、负号情况不添加分隔符。
#include <iostream>
#include <string>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
int c=a+b;
string num=to_string(c); //存为string类型
string ans; //结果存入string类型的ans
for(int i=num.size()-1,j=0;i>=0;i--){ //逆序遍历string内;
ans=num[i]+ans; //逐字符添加,注意是从低位到高位添加进ans
j++; //计数添加了的数位
if(j%3==0&&i&&num[i-1]!='-'){ //从低位到高位计数下,每隔三位向ans头部插入逗号,排除负号、首位i=0情况
ans=','+ans;
}
}
cout<<ans;
return 0;
}
【总结】
涉及到的三位分节法的格式要求有、头大,重点是要把握从低位到高位每隔三位逗号分隔,首位排除的特性编码(解法2、3),而从高位往低位处理,则需要把握 首节位数 为插入分隔符的基数(首插),以此往后每隔三位插入分隔符,末位排除(解法1)。