贝壳第一题相邻数的差,用字符串存储也没AC?
RT,楼主用的是 C++,一开始直接用 int 存,发现不对,后来改为 long long,还是不对
最后用字符串模拟减法,也只得到了 0.91,这道题写了好久,心态崩了。。
有朋友能检查检查我的代码么:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
bool cmp(string a, string b) {
if (a.length() > b.length())
return true;
else if (a.length() == b.length())
return a > b;
return false;
}
string sub(string a, string b) {
// 默认 a > b
string res;
if (false == cmp(a, b)) return sub(b, a);
int i, j;
int bit = 0;
for (i = a.length() - 1, j = b.length() - 1; i >= 0, j >= 0; --i, --j) {
int tempA = a[i] - '0';
int tempB = b[j] - '0';
tempA -= bit;
bit = 0;
if (tempA < tempB) {
tempA += 10;
bit = 1;
}
res += to_string(tempA - tempB);
}
for (i; i >= 0; --i) {
int tempA = a[i] - '0';
if (bit > 0) {
tempA -= bit;
bit = 0;
}
if (tempA < 0) {
tempA += 10;
bit = 1;
}
res += to_string(tempA);
}
reverse(res.begin(), res.end());
return res;
}
int main ()
{
int N;
string res = "99999999999999999999999999999999999999999";
string a, b;
cin >> N;
string * arr = new string [N + 1];
for (int i = 0; i < N; ++i) {
cin >> arr[i];
}
for (int i = 0; i < N - 1; ++i) {
string thisRes = sub(arr[i], arr[i + 1]);
if (cmp(res, thisRes)) {
res = thisRes;
a = arr[i];
b = arr[i + 1];
}
}
cout << a << " " << b;
delete [] arr;
return 0;
} 

查看1道真题和解析