PAT C++ Java Python 1001 A+B format string的使用

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

题目分析

可以在int范围内,表示加数与和。采用从右向左,三位增加一个“,”。
解题思路:首先计算两个int型 a+b=c
然后对c进行处理,将c转换为字符串型,然后计算字符串的长度,增加合适的“,”即可。
c可能大于0,也可能小于0,为了方便处理,当c小于零时,我们对c进行取反,输出“-”。
举个例子对于10,000的输出,可以让字符串的长度mod3=2,于是输出两位,后边输出**,3位**,知道输出完毕。
三种情况分别分析,即可获得结果,length%3=(0,1,2),具体分析见以下代码。

#include 
#include 
using namespace std;
int main()
{
     
	int i=0,j,a,b,c;
	cin>>a>>b;
	c=a+b;
	if(c==0){
      //如果结果是0,直接输出,程序结束
	  cout<<0<<endl;
	  return 0;	
	}
		
	if(c<0)
	{
     
		cout<<'-';
		c=-c;
	}
	//以下是对int转换为char*的处理
	char s[20],t[20];
	a=c;
	while(a){
     
		t[i++]=a%10+'0';
		a/=10;
	}
	j=0;
	i--;
	while(i>=0){
     
		s[j++]=t[i--];
	}
	s[j]='\0';
	/***********************************/
	
	int length=strlen(s);
	if(length<4){
      //如果长度小于4,则直接输出 
		cout<<s<<endl;
	}
	else{
      //长度大于4的情况,需要进行加,处理 
		int i,k=0; 
		i=length%3;
		if(i==0){
     
			cout<<s[0]<<s[1]<<s[2];
			k=3;
		}
		else if(i==1){
     
			cout<<s[0];
			k=1;
		}
		else if(i==2){
     
			cout<<s[0]<<s[1];
			k=2;	
		}
		while(k<length){
     
			cout<<','<<s[k]<<s[k+1]<<s[k+2];
			k+=3;
		}
	}	
	return 0;
}

起初我使用了itoa()函数将int转换为char*,自己运行没一点问题,但是提交的时候,编译器不识别itoa(),所以只好自己写了一下itoa函数的功能。


更新,其实itoa的功能可以直接用 **sprintf()**来实现,sprintf(str,"%d",int); 以下是我二刷的代码,直接使用reverse()先把字符串逆过来,添加‘,’,然后再次求逆,可获得结果。
#include 
#include 
#include 
#include 
using namespace std;
int main()
{
     
    int a,b,c;
    char str[10];
    scanf("%d%d",&a,&b);
    c=a+b;
    if( c<0 )
    {
     
        printf("-");
        c=-c;
    }
    sprintf(str,"%d",c);
    string s(str);
    string ans;
    reverse(s.begin(),s.end());
    for(int i=0;i<s.length();i++)
    {
     
        if(i&&i%3==0)
          ans+=','; //字符串连接功能
        ans+=s[i];
    }
    reverse(ans.begin(),ans.end());
    cout<<ans<<endl;
    return 0;
}

Java Python C++格式化输出

Java和Python可以直接格式化输出

Java代码

import java.util.Scanner;

public class Main {
     
    public static void main(String[] args) {
     
        int a, b;
        Scanner scanner = new Scanner(System.in);
        a = scanner.nextInt();
        b = scanner.nextInt();
        System.out.printf("%,d", a+b);
    }
}

python3代码

s = list(input().split())
print( format(int(s[0]) + int(s[1]), ','))
# {:,}.format(int(s[0])+int(s[1]))

你可能感兴趣的:(PAT,OJ试题,PAT,python,c++,java)