PAT1001 A+B Format Practice Experience

I just want to write this to record some problems I encountered in the process of brushing PAT and my own summary.
My current situation is: I have learned C language and data structure, JAVA language, and C++ are only half-knowledgeable, and I have not mastered all of them. Therefore, in the process of brushing the questions, I also record the learning of C++.

1001 A+B Format

1. First of all, the difficulty of this question is that for the output of commas, a comma must be output for every three digits. If the output is in the form of numbers, the problem of zero will be considered. For example, the result after addition is 100002. The actual output display should be " 100,002", but in digital form, when taking the last three digits, only 2 will be obtained anyway, and the previous 0 will be automatically omitted, and the display result will display "100,2", so the final output cannot be in digital form. The result must be converted to a string for processing.
2. C++ number conversion to string method

#include <string>
#include <sstream>
#include <iostream> 
using namespace std;
int main(){
    
    
    double a = 123.32;
    string res;
    stringstream ss;
    ss << a;
    ss >> res;//或者 res = ss.str();
    cout<<res; 
    return 0;
}

3. Consider whether the range of addition is reasonable. The title requires −10​6​≤a, b≤10​6​, and the range of int in C++ is -2147483648 to 2147483647, which can represent the range of 10^9, so this The consideration of the question is simple, just perform integer addition. After passing this point, when inquiring about other methods, I realized it through other people's analysis.
4. Learn from other people's methods and realize that for the treatment of commas, you can actually put the numbers upside down into the number array first, and then process the subscripts. Commas can be added before or after the subscripts that are divisible by 3, depending on the situation. .
5. Code I wrote

#include<iostream>
#include<string>
#include<sstream>
using namespace std;
void print(int s){
    
    
	int n=0,m=s,p=0,i=0;
	string str="";
	stringstream ss;
	while(abs(m/1000)>0){
    
    
		m = m/1000;
		n++;	
	}
	m=s;
	if(n>0){
    
    
		ss << m;
		ss >> str;	//转换为字符串,通过n判断需要加入,的次数	
		while(n){
    
    
			i=3*n;
			str.insert(str.length()-i,",");
			n--;
		}
		cout<<str;
	}
	else{
    
    
		printf("%d",s);
	}
}

int main(){
    
    
	int a,b,sum;
	scanf("%d %d",&a,&b);
	sum = a + b;
	print(sum);
	return 0;
} 

Guess you like

Origin blog.csdn.net/weixin_44696740/article/details/104030611