甲级PAT1001 A+B Format

1001 A+B Format (20)(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

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

 题目要求:

计算A+B的和并按要求格式输出。数字三个为一组用逗号隔开(除非数字少于四个)

解题思路:

这里重点是输出格式,由于a和b的范围在int型范围之内,直接加法就可。输出格式我比较喜欢用字符串控制,所以先将计算后的值转化成字符串。根据字符串的长度可以算出需要插多少个逗号以及开始插入的位置。(根据除以三和余三就可以得到)

注意:

1.位数少于三位直接输出

2.若余数恰好为0,此时的开始位置要为3而不是0,这点一定要注意。

3.正负的处理不同,是因为负数要比正数多一个负号。因此可以先通过erase()函数去掉负号,同正数一起处理即可。最后按格式保存后再把负号加上就可以了。

完整代码:

#include<iostream>
#include <sstream>
#include<string>
using namespace std;

int main(){
  int a,b,sum;
  stringstream ss;
  string s,result;
  int i,x,y;
  result = "";
  cin>>a>>b;
  sum = a + b;
  ss << sum;
  ss >> s;
  if(sum>=0){
    x = s.length()/3;
    y = s.length()%3;
    if(x<1){
      cout<<s<<endl;
    }else if(y==0){
      for(i=3;i<=s.length()-3;i=i+4){
        s.insert(i,",");
      }
      cout<<s<<endl;
    }else{
      for(i=y;i<=s.length()-3;i=i+4){
        s.insert(i,",",1);
      }
      cout<<s<<endl;
    }
  }else{
  	s.erase(0,1);
    x = s.length()/3;
    y = s.length()%3;
    if(x<1){
      s.insert(0,"-");
      cout<<s<<endl;
    }else if(y==0){
      for(i=3;i<=s.length()-3;i=i+4){
        s.insert(i,",");
      }
      s.insert(0,"-");
      cout<<s<<endl;
    }else{
      for(i=y;i<=s.length()-3;i=i+4){
        s.insert(i,",",1);
      }
      s.insert(0,"-");
      cout<<s<<endl;
  	}
  }
  return 0;
}

笔记:

1.int型和long long型的范围

int                  所占字节数为:4                   表示范围为:-2147483648~2147483647

long long     所占字节数为:8       表示范围为:9223372036854775808~+9223372036854775807

2.stringstream类

可将string类型转化为int类型,也可以将int型转化为string类型

点赞