高精度加法
#include<iostream>
using namespace std;
string s1 ,s2;
int a[101], b[101];
int c[101];
void strtoint(string src, int des[]){
for (int i = 0; i < src.size(); i++) {
des[src.size() - i] = src[i] - '0';
}
}
int main(){
cin >> s1 >> s2;
// 1.个位对齐-反转des, 字符转整型
strtoint(s1, a);
strtoint(s2, b);
int la = s1.size(), lb = s2.size();
//2.计算c数组的长度(按最长数位计算)
int lc = max(la, lb) + 1;
//3.对位相加得出c数组
for (int i = 1; i <= lc; i++) {
c[i] = a[i] + b[i] + c[i];
c[i + 1] = c[i] / 10;
c[i] %= 10;
}
//4.去除前导0
while (c[lc] == 0 && lc > 1) lc--;
//5.倒叙打印
for (int i = lc; i >= 1; i--) {
cout << c[i];
}
return 0;
}
高精度减法
#include<iostream>
using namespace std;
string s1 ,s2;//高精度
int a[101], b[101], c[101];
void strtoint(string src, int des[]) {
for (int i = 0; i < src.size(); i++) {
des[src.size() - i] = src[i] - '0';
}
}
bool cmpstr(string strl, string str2) {
if (strl.size() != str2.size())
return strl.size() > str2.size();
else
return strl >= str2;
}
int main(){
cin >> s1 >> s2;
if (cmpstr(s1, s2) == false) {
string s3 = s1; //swap(s1, s2)也可以
s1 = s2;
s2 = s3;
cout << "-";
}
int la = s1.size(), lb = s2.size();
strtoint(s1, a);
strtoint(s2, b);
int lc = max(la, lb);
for (int i = 1; i <= lc; i ++ ) {
if (a[i] < b[i]) {//不够减
a[i + 1]--;//向高一位借位
a[i] += 10;//借1当10用
}
c[i] = a[i] - b[i];
}
while (c[lc] == 0 && lc > 1) lc--;
for (int i = lc; i >= 1; i--) {
cout << c[i];
}
return 0;
}
高精度乘法
#include<iostream>
using namespace std;
// 高精度乘法
string s1, s2;
int a[201], b[201], c[201];
void strtoint(string src, int des[]) {
for (int i = 0; i < src.size(); i++) {
des[src.size() - i] = src[i] - '0';
}
}
int main() {
cin >> s1 >> s2;
strtoint(s1, a);
strtoint(s2, b);
int la = s1.size(), lb = s2.size();
int lc =la + lb;
for (int i = 1; i <= la; i++) {
for (int j = 1; j <= lb; j++) {
c[i + j - 1] += a[i] * b[j];
c[i + j] += c[i + j - 1] / 10;
c[i + j - 1] %= 10;
}
}
while (c[lc] == 0 && lc > 1) lc--;
for (int i = lc; i >= 1; i--) {
cout << c[i];
}
return 0;
}
高精度除法(具体为高精度/低精度)
#include<iostream>
using namespace std;
// 高精度除法(高精度/低精度)
// 高精度除法(高精度/高精度)极其复杂!!!!!!!
string s;
int a[101], c[101];//高精度
long long b;//低精度
int tmp;
void reverseStrtoInt(string s, int* a) {
for (int i = 0; i < s.size(); i++) {
a[i + 1] = s[i] - '0';
}
}
int main() {
cin >> s;
cin >> b;
int la = s.size();
reverseStrtoInt(s, a);
for (int i = 1; i <= la; i++) {
c[i] = (tmp * 10 + a[i]) / b;
tmp = (tmp *10 +a[i]) % b;
}
int lc = 1;
while(c[lc] == 0 && lc < la) lc++;
for (int i = lc; i <= la; i++) {
cout << c[i];
}
cout << endl << tmp;
return 0;
}