[#181024][PAT Practice] A+B Format
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表現更穩定些。
相關文章
- PAT:1001 A+B Format (20分)ORM
- [PAT B] 1011 A+B 和 C
- PAT-B 1016 部分A+B
- PAT-B 1093 字串A+B 【集合】字串
- PAT-B 1011 A+B 和 C
- 1003 我要通過!| PAT (Basic Level) Practice
- PAT答案(D進位制的A+B)
- PAT (Advanced Level) Practice 1149 Dangerous Goods Packaging (25分)Go
- PAT (Basic Level) Practice (中文)-1009-說反話 (20分)
- 【PTA甲級、C++簡單解答】1001 A+B Format (20分)C++ORM
- PAT-B 1022 D進位制的A+B【進位制】
- 【PAT甲級A1065】A+B and C (64bit) (20分)(c++)C++
- PAT (Basic Level) Practice 1001 害死人不償命的(3n+1)猜想
- Practice
- airflow practiceAI
- A+B
- scientifically practice DP
- shell practice 03
- shell practice 04
- shell practice 05
- shell practice 06
- shell practice 07
- As Easy As A+B
- Format and un-format money/currency in JavaScriptORMJavaScript
- PAT B1022 D進位制的A+B(進位制轉換板題,簡單模擬)
- Practice| 流程控制
- A+B問題
- Json formatJSONORM
- 求助:TypeError: unsupported format string passed to NoneType.__format__ErrorORMNone
- Vegetables need more practice.
- hdu 1720 A+B Coming
- set excel formatExcelORM
- yolov5s ncnn practiceYOLOCNN
- 問題解決:TypeError: unsupported format string passed to NoneType.__format__ErrorORMNone
- [Algorithm] 1. A+B ProblemGo
- 1016. 部分A+B (15)
- [Ruby]format xml with RubyORMXML
- oracle工具 awr formatOracleORM