刷題筆記本——1:PAT (Advanced Level) Practice 1001 A+B Format (20)(20 分)
來自專欄給我一把過去的電鋸
題目鏈接:
PTA | 程序設計類實驗輔助教學平台解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結果是全部通過
代碼如下:
- #include <iostream>
- #include <cstdio>
- int main(int argc, const char * argv[]) {
- int a, b, sum;
- scanf("%d %d", &a, &b);
- sum = a + b;
- if(sum == 0) printf("0");
- if(sum < 0){
- printf("-");
- sum = -sum;
- }
- int str[10];
- int k = 0;
- while(sum > 0) {
- str[k] = sum % 10;
- sum /= 10;
- k++;
- }
- for (int i = k - 1; i >= 0; i--) {
- printf("%d",str[i]);
- if(i % 3 == 0 && i > 0) printf(",");
- }
- return 0;
- }
推薦閱讀:
※語文最怕碰到古詩詞鑒賞?刷題都沒用?1張表2個步驟幫你全搞定!
※不會英語也能做SWT!你還在大量刷題?掌握技巧15分鐘就能輕鬆得高分!!
TAG:刷題 |