今天闲的没事想写一个重载运算符的string高精
写着写着发现,string原来已经有了加法操作(连接)
如果重载运算符,在main和其他函数中都可以调用
但是在重载的高精乘高精的运算符的函数(?)调用就会调用成原来的连接操作
这里只好先用原来没有的“%”代替加号来调用高精度加法
各位dalao有没有办法可以避免这个问题?
代码如下:
#include<bits/stdc++.h>
using namespace std;
bool operator< (const string& __x, const string& __y) {
if (__x.length() < __y.length())return 1;
if (__x.length() > __y.length())return 0;
for (int i = __x.length() - 1; i > 0; i--)
if (__x[i] != __y[i])return __x[i] < __y[i];
return 0;
}
bool operator> (const string& __x, const string& __y) {
if (__x.length() > __y.length())return 1;
if (__x.length() < __y.length())return 0;
for (int i = __x.length() - 1; i > 0; i--)
if (__x[i] != __y[i])return __x[i] > __y[i];
return 0;
}
string operator%/*+*/ (const string& __a, const string& __b) {//由于string之间的+已经有操作,这里不得不用 "%" 代替
// cout << 1 << endl;
if (__a == "0")return __b;
if (__b == "0")return __a;
int jw = 0, now;
string ret, a, b;
a = __a, b = __b;
if (a.length() < b.length()) swap(a, b);
ret = a;
for (int i = a.length() - 1, j = b.length() - 1; j >= 0; i--, j--) {
now = a[i] - '0' + b[j] - '0' + jw;
jw = now / 10;
now %= 10;
ret[i] = now + '0';
}
for (int i = a.length() - b.length() - 1; i >= 0 && jw; i--)
if (a[i] == '9')ret[i] = '0';
else {
ret[i] = a[i] + jw;
jw = 0;
break;
}
if (jw)ret.insert(0, "1");
return ret;
}
string operator* (const int& __a, const string& __b) {
if (__a == 0)return "0";
if (__b == "0")return "0";
string ret = __b;
int jw = 0, now;
for (int i = __b.length() - 1; i >= 0; i--) {
now = (__b[i] - '0') * __a + jw;
jw = now / 10;
now %= 10;
ret[i] = now + '0';
}
string __jw = " ";
__jw[0] = jw + '0';
if (jw)ret.insert(0, __jw);
// cout << ret << endl;
return ret;
}
string operator* (const string& __a, const string& __b) {
if (__a == "0" || __b == "0")return "0";
string ret = "0", a, b;
a = __a, b = __b;
if (a.length() < b.length())swap(a, b);
for (int i = 0; i < b.length(); i++) {
ret = 10 * ret;
ret = ret %/*+*/ string((int(b[i] - '0')) * a);
}
return ret;
}
int main() {
string a;
string b;
cin >> a >> b;
cout << a * b;
}
写的可能比较史,并且在高精度乘法的函数里面偷了个懒直接写了累加
模板题已通过,提交记录