c++的高精

python自带高精,Java也有BigInteger和BigDecimal类,c++。。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <bits/stdc++.h>
using namespace std;

class BigInteger {
public:
//获取snum字符串,setup()转换成数组
string snum = "";
vector<size_t> num;

//构造器,定义vector大小。。
BigInteger() {
num.resize(40000);
}

void setup() {
//为了思考方便些,把数字颠倒过来。。
std::reverse(snum.begin(), snum.end());
for (int i = 0, l = snum.length(); i < l; ++i)
num[i] = snum[i] - '0';
return;
}

//相加,直接在这个对象上面加
string add(BigInteger b) {
if (snum == "0") return b.snum;
if (b.snum == "0") return snum;

//用stringstream记录每次相加的过程
stringstream ss;
for (int i = 0, l = max(snum.length(), b.snum.length()); i <= l; ++i) {
num[i] += b.num[i];
//其实直接第一个++,第二个-=10就行
if (num[i] > 9) {
num[i + 1] += num[i] / 10;
num[i] = num[i] % 10;
}
ss << num[i];
}

//直接转成字符串颠倒去头部0输出
string s = ss.str();
std::reverse(s.begin(), s.end());

int i = 0;
for (int l = s.length(); i < l; ++i)
if (s[i] != '0') break;

return s.substr(i);
}

string times(BigInteger b) {
//跟上面差不多,如果是0返回0,如果是1返回另外一个
if (snum == "0" || b.snum == "0") return "0";
if (snum == "1") return b.snum;
if (b.snum == "1") return snum;

//这里用的是另外一个temp对象来储存..
BigInteger temp;
//还是用stringstream储存输出
stringstream ss;

for (int i = 0, l1 = snum.length(); i <= l1; ++i) {
for (int j = 0, l2 = b.snum.length(); j <= l2; ++j) {
temp.num[i + j] += num[i] * b.num[j];
if (temp.num[i + j] > 9) {
temp.num[i + j + 1] += temp.num[i + j] / 10;
temp.num[i + j] = temp.num[i + j] % 10;
}
}
}

for (int i = 0, l = temp.num.size(); i < l; ++i)
ss << temp.num[i];

string s = ss.str();
std::reverse(s.begin(), s.end());

int i = 0;
for (int l = s.length(); i < l; ++i)
if (s[i] != '0') break;

return s.substr(i);
}
};

int main() {

//Add
/*BigInteger i1, i2;
cin >> i1.snum >> i2.snum;

i1.setup();
i2.setup();

cout << i1.add(i2);*/

//Multiply
BigInteger b1, b2;
cin >> b1.snum >> b2.snum;

b1.setup();
b2.setup();

cout << b1.times(b2);
return 0;
}

这里只有加和乘,剩下的还没写

测试一下乘法:

In:

999999999999999999999999999999

233336666699990000651919556666

Out:

233336666699990000651919556665766663333300009999348080443334

跟python算的一样没错

还有加法:

In:

999999999999999999999999999999

233336666699990000651919556666

Out:

1233336666699990000651919556665

一样+1

评论

:D 一言句子获取中...

加载中,最新评论有1分钟缓存...