PAT(Advanced Level)1001 A+B Format

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 −10​6​​≤a,b≤10​6​​. 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
/*	Sample Input:-1000000 9
	Sample Output:-999,991
*/
#include <iostream>
#include <algorithm> 
#include <string>
using namespace std;
int main(){
	int a, b, sum;
	cin >> a >> b;
	sum = a + b;
	string s = to_string(sum);//转化为字符型数组
	if(s[0] == '-') {
		cout << "-";
		s.erase(0, 1); //删除从下标从0开始的一个字符 
	}
	reverse(s.begin(), s.end());//由于添加","从后往前加的,所以需要先转置一下
	int len = (int)s.size();
	for(int i = 3; i < len; i += 3) { //每隔3个数字插入一个"," 
		s.insert(i, ",");
		i++; //插完的","也算一个位置的,故要往后移一位的
		len++; //插入","以后s的总长度要加1 
	}	
	reverse(s.begin(), s.end());
	cout << s; 
	return 0;
}

string字符串操作:

  • erase
    原型:
    (1)string& erase ( size_t pos = 0, size_t n = npos );
    (2)iterator erase ( iterator position );
    (3)iterator erase ( iterator first, iterator last );
    用法:
    (1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
    (2)erase(position);删除position处的一个字符(position是个string类型的迭代器)
    (3)erase(first,last);删除从first到last之间的字符(first和last都是迭代器)

  • insert
    原型:
    string &insert(int p0, const char *s);
    string &insert(int p0, const char *s, int n);
    string &insert(int p0,const string &s);
    string &insert(int p0,const string &s, int pos, int n);
    //前4个函数在p0位置插入字符串s中pos开始的前n个字符
    string &insert(int p0, int n, char c);//此函数在p0处插入n个字符c
    iterator insert(iterator it, char c);//在it处插入字符c,返回插入后迭代器的位置
    void insert(iterator it, const_iterator first, const_iterator last);//在it处插入[first,last)之间的字符
    void insert(iterator it, int n, char c);//在it处插入n个字符c

  • to_string函数 C++11 新增方法
    string to_string (int val);
    string to_string (long val);
    string to_string (long long val);
    string to_string (unsigned val);
    string to_string (unsigned long val);
    string to_string (unsigned long long val);
    string to_string (float val);
    string to_string (double val);
    string to_string (long double val)

  • reverse函数
    数组转置 reverse(v.begin(),v.end())

猜你喜欢

转载自blog.csdn.net/wangjian530/article/details/83184002
今日推荐