PAT 1001. A+B Format (20)(C++)

Title description

Insert picture description here
When I first got this question, I didn’t know that C++ also has a function to convert numbers to strings. I wrote a tostring by hand, but the converted string is inverted. Some situations are not considered comprehensively when outputting, resulting in not all correctness. It took a few times to change everything, and the code was cumbersome and lengthy.

#include<iostream>
#include<string>
using namespace std;
string tostring(int num){
    
    
	if(num ==  0 )
	return "0";
	string result="";
	while(num!=0){
    
    
		result+ =(char)(num%10+'0');
		num/=10;
	}
	return result;
}
int main(){
    
    
	int a,b;
	while(cin>>a>>b){
    
    
	int sum = a+b;
	if(sum<0)
	{
    
    
	cout<<"-";
	sum= -sum;
	}
	string result= tostring(sum);
	int num  =0;
	int tem = result.length()%3;
	int i;
	for(i = result.length()-1;tem>0;tem --,i--){
    
    
		cout<<result[i];
		if( tem  == 1&&result.length()>3)
		cout<<",";
	}
	for(;i>=0;i--){
    
    
		cout<<result[i];
		num++;
		if(num == 3){
    
    
			if(i==0)
			continue;
			cout<<",";
			num=0;
		}
	}
	cout<<endl;
}
}

Then I checked other people’s code online and found that it only takes a few lines to solve it (I’m still too good at it)

Solution 1

Mainly use string processing. to_string converts numbers to strings. In addition, in order to avoid when the number of digits is exactly a multiple of three, when i=0, output',', so i!=0 is added to the judgment condition;

#include <iostream>
#include <string>
using namespace std;
int main(){
    
    
	int a,b;
	cin>>a>>b;
	if(a+b<0)
		cout<<'-';
	string s=to_string(abs(a+b));
	int d=(s.length())%3;
	for(int i=0;i<s.length();i++){
    
    
		if(i!=0&&i%3==d)
			cout<<',';
		cout<<s[i];
	}
}

Solution 2

Assuming that the length of the char array or string obtained is len, find the value of len%3. If the value is not 0, if it is 2, first output the previous len%3 bits, and output a "," Then output 3 digits in the form of output; if the value is 0, output the first three digits first, and output the rest in the form of outputting a "," and then outputting 3 digits.

#include<bits/stdc++.h>
using namespace std;
int main(){
    
    
    int a,b;
    cin>>a>>b;
    if(a+b<0)
        cout<<"-";
    string s=to_string(abs(a+b));
    int i=s.size()%3==0?3:s.size()%3;
    cout<<s.substr(0,i);
    for(;i<s.size();i+=3)
        cout<<","<<s.substr(i,3);
    return 0;
}

Guess you like

Origin blog.csdn.net/qaqaqa666/article/details/112509942