题目描述
本人菜鸟一枚,各位大佬轻喷
C++ 代码
#include <iostream>
#include <string>
using namespace std;
bool check(int q[],int p[],int n){
for(int i=n-1;i>=0;i--){
if(q[i]>p[i])return false;
if(q[i]==p[i])continue;
if(q[i]<p[i])return true;
}
return false;
}//检查q[i]代表的数是否小于p[i]代表的数
int check0 (int f[],int n){
if(f[n-1]!=0)return n-1;
else for(int i=n-1;i>=0;i--){
if(f[i]!=0)return i+1;
else continue;
}
}
bool check_all_0(int f[],int n){
for(int i=0;i<n;i++){
if(f[i]!=0)return false;
}
return true;
}
int main() {
const int N = 1e5 + 10;
string a, b;
int q[N] = { 0 }, p[N] = { 0 };
cin >> a >> b;
int n = a.size(), m = b.size();
for (int i = 0; i < n; i++)q[i] = a[n-i-1]-48;
for (int i = 0; i < m; i++)p[i] = b[m-i-1]-48;
int f[N] = { 0 };
if (n == m) {
if(check(q,p,n)){
for(int i=0;i<n;i++){
int a=p[i];
p[i]=q[i];
q[i]=a;}
for (int i = 0; i < n; i++) {
int g=f[i];
f[i]+=q[i]-p[i];
if (f[i] < 0) {
f[i] = g+q[i] + 10-p[i];
f[i + 1] -= 1;
}
}
int max = m > n ? m : n;
if(f[max-1]!=0)cout <<"-"<< f[max-1];
else cout<<"-";
for (int i = 1; i <= check0(f,max); i++) {
cout << f[check0(f,max)-i];}
}
else {for (int i = 0; i < n; i++) {
int g=f[i];
f[i]+=q[i]-p[i];
if (f[i] < 0) {
f[i] = g+q[i] + 10-p[i];
f[i + 1] -= 1;
}
} int max = m > n ? m : n;
if(check_all_0(f,max))cout<<"0";
else{if (f[max-1] != 0)cout << f[max-1];
for (int i = 1; i <= check0(f,max); i++) {
cout << f[check0(f,max)-i];}
}
}
}
else if (n > m) {
for (int i = 0; i < m; i++) {
int g=f[i];
f[i] += q[i] - p[i];
if (f[i] < 0) {
f[i] =g + q[i] + 10-p[i];
f[i + 1] -= 1;
}
}
for (int j = 1; j <= n - m; j++) {
f[m - 1 + j] += q[m - 1 + j];
if (f[m - 1 + j] < 0) {
f[m - 1 + j] = f[m - 1 + j] + 10;
f[m + j] -= 1;
}
}
int max = m > n ? m : n;
if (f[max-1] != 0)cout << f[max-1];
for (int i = 1; i < max; i++) {
cout << f[max-i-1];
}
}
else if (n < m) {
for (int i = 0; i < n; i++) {
int g=f[i];
f[i] += p[i] -q[i];
if (f[i] < 0) {
f[i] = g+p[i]+ 10-q[i];
f[i + 1] -= 1;
}
}
for (int j = 1; j <= m - n; j++) {
f[n - 1 + j] += p[n - 1 + j];
if (f[n - 1 + j] < 0) {
f[n - 1 + j] = f[n - 1 + j] + 10;
f[n + j] -= 1;
}
}
int max = m > n ? m : n;
if (f[max-1] != 0)cout <<"-"<< f[max-1];
for (int i = 1; i < max; i++) {
cout << f[max-i-1];
}
}
}