[#181024][PAT Practice] A+B Format

EdwardTex發表於2018-10-31

A+B Format

Qustion

時間限制 400ms
記憶體限制 65536KB
程式碼長度限制

16000B

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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

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

 

Thought&Answer

Common

題目唯一有難點的地方是對計算結果加逗號,常規處理的方案的話,利用字串和陣列處理計算所得結果

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
int c=a+b;
if(c<0) cout<<'-';
c=abs(c);
char s[20];
sprintf(s,"%d",c);
int len=strlen(s);
int m=len/3,n=len%3,start=0;
if(n==0) {cout<<s[0]<<s[1]<<s[2];start=3;m--;}
else if(n==1) {cout<<s[0];start=1;}
else if(n==2) {cout<<s[0]<<s[1];start=2;}
while(m!=0){
cout<<',';
cout<<s[start]<<s[start+1]<<s[start+2];
start+=3;
m--;
}
return 0;
}

Trick

題目已經說明兩數字在[-10^6,10^6]之間,所以sum的範圍也就在[-210^6,210^6]之間,只需考慮最長7位的情況即可

#include<iostream>
#include<cstdio>
using namespace std;
int main(){
    int a,b;
    cin>>a>>b;
    int c=a+b;
    if(c<0){cout<<'-';c=-c;}
    if(c>=1000000){
        printf("%d,%03d,%03d",c/1000000,c%1000000/1000,c%1000);
    }else if(c>=1000){
        printf("%d,%03d",c/1000,c%1000);
    }else{
        printf("%d",c);
    }
    return 0;
}

Experience

1.就最快AC為第一原則,顯然Trick不應該作為Trick出現,而應該是最該優先被考慮的解法;
2.對執行時間和記憶體限制沒有概念,對程式碼長度按檔案大小衡量沒有概念,慢慢地應該會有改善;
3.本題中測試點為12個,相對來講#Trick比#Common表現更穩定些。

 

 

相關文章