PAT1001

    科技2022-07-14  140

    PAT 1001

    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

    #include<iostream> #include<sstream> #include<string> using namespace std; string itos(int num){ stringstream s; s<<num; return s.str(); } int main(){ int a,b,sum=0; cin>>a>>b; sum=a+b; string s; s=itos(sum); for(int i=0;i<s.length();i++){ cout<<s[i]; if(s[i]=='-'){ continue; } // s is began from the high position such as 4000, // begin as 4 not zero. if((i+1)%3==s.length()%3&&i!=s.length()-1){ cout<<","; } } return 0; }

    字符串流,这里用到最基础的功能,int转string类型,首先定义一个stringstream类型的变量s,将int型变量sum,输入流,输出转换后的字符串,返回到主函数。

    JAVA复现

    import java.io.*; public class Main { public static void cal() throws IOException{ BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in)); String[] strArr=buffer.readLine().split(" "); int a=Integer.parseInt(strArr[0]); int b=Integer.parseInt(strArr[1]); char[] res = String.valueOf(a + b).toCharArray(); if(res.length>3){ for(int i=0;i<res.length;i++){ System.out.print(res[i]); if(res[i]=='-'){ continue; } if((i+1)%3==res.length%3&&i!=res.length-1){ System.out.print(","); } } }else{ for(int i=0;i<res.length;i++){ System.out.print(res[i]); } } } public static void main(String[] args) throws IOException{ cal(); } }

    JAVA做PAT一定要对输入输出流进行优化,不然会超时。

    Processed: 0.011, SQL: 8