標籤:

刷題筆記本——1:PAT (Advanced Level) Practice 1001 A+B Format (20)(20 分)

刷題筆記本——1:PAT (Advanced Level) Practice 1001 A+B Format (20)(20 分)

來自專欄給我一把過去的電鋸

題目鏈接:

PTA | 程序設計類實驗輔助教學平台?

pintia.cn

解1:用reverse翻轉字元串

#include<iostream>

#include<string>

#include<algorithm>

using namespace std;

int main() {

int i = 1, a, b,sum;

bool is_positive=false;

cin >> a >> b;

sum = a + b;

string str;

if (sum<0) {

is_positive = true;

sum = 0-sum;

}

while (sum) {

char ch = 0 + sum%10;

sum /= 10;

if (i % 4==0) {

str.push_back(,);

i = 1;

}

str.push_back(ch);

i++;

}

reverse(str.begin(), str.end());

if (is_positive) {

cout << -;

}

cout << str << endl;

return 0;

}

結果不知道為何總有一個測試用例通不過

解2:不用演算法庫的做法

#include<iostream>

using namespace std;

int main() {

int a, b, sum, i, f = 0;

bool is_positive = false;

char s[9];

cin >> a >> b;

sum = a + b;

if (sum < 0) {

is_positive = true;

sum = 0 - sum;

}

if (sum > 1000) {

for (i = 0; sum > 0; i++) {

s[i] = sum % 10 + 0;

sum = sum / 10;

if (f == 2 && sum != 0) {

i++;

s[i] = ,;

f = 0;

}

else

{

f++;

}

}

if (is_positive) {

s[i] = -;

cout << s[i];

}

i--;

for (; i >= 0; i--) {

cout << s[i];

}

cout << endl;

}

else

{

cout<<sum<<endl;

}

return 0;

}

結果更慘了,兩個測試用例沒通過o(╥﹏╥)o

PS:參考以下鏈接的代碼:

https://blog.csdn.net/phoenix_wei/article/details/79209726?

blog.csdn.net

結果是全部通過

代碼如下:

  1. #include <iostream>
  2. #include <cstdio>
  3. int main(int argc, const char * argv[]) {
  4. int a, b, sum;
  5. scanf("%d %d", &a, &b);
  6. sum = a + b;
  7. if(sum == 0) printf("0");
  8. if(sum < 0){
  9. printf("-");
  10. sum = -sum;
  11. }
  12. int str[10];
  13. int k = 0;
  14. while(sum > 0) {
  15. str[k] = sum % 10;
  16. sum /= 10;
  17. k++;
  18. }
  19. for (int i = k - 1; i >= 0; i--) {
  20. printf("%d",str[i]);
  21. if(i % 3 == 0 && i > 0) printf(",");
  22. }
  23. return 0;
  24. }

推薦閱讀:

語文最怕碰到古詩詞鑒賞?刷題都沒用?1張表2個步驟幫你全搞定!
不會英語也能做SWT!你還在大量刷題?掌握技巧15分鐘就能輕鬆得高分!!

TAG:刷題 |