Skip to content

Commit 77b80e2

Browse files
committed
改为64位
1 parent 4d59e41 commit 77b80e2

File tree

2 files changed

+19
-14
lines changed

2 files changed

+19
-14
lines changed

C++/LeetCodet题解(C++版).pdf

1.74 KB
Binary file not shown.

C++/chapImplement.tex

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,9 @@ \subsubsection{描述}
277277

278278

279279
\subsubsection{分析}
280-
280+
高精度乘法。
281+
282+
常见的做法是将字符转化为一个int,一一对应,形成一个int数组。但是这样很浪费空间,一个int32的最大值是$2^{31}-1=2147483647$,可以与9个字符对应,由于有乘法,减半,则至少可以与4个字符一一对应。一个int64可以与9个字符对应。
281283

282284

283285
\subsubsection{代码}
@@ -291,7 +293,7 @@ \subsubsection{代码}
291293
* @return 无
292294
*/
293295
BigInt(string s) {
294-
vector<int> result;
296+
vector<int64_t> result;
295297
result.reserve(s.size() / RADIX_LEN + 1);
296298

297299
for (int i = s.size(); i > 0; i -= RADIX_LEN) { // [i-RADIX_LEN, i)
@@ -302,7 +304,7 @@ \subsubsection{代码}
302304
}
303305
result.push_back(temp);
304306
}
305-
n = result;
307+
elems = result;
306308
}
307309
/**
308310
* @brief 将整数转化为字符串.
@@ -311,9 +313,9 @@ \subsubsection{代码}
311313
string toString() {
312314
stringstream result;
313315
bool started = false; // 用于跳过前导0
314-
for (auto i = n.rbegin(); i != n.rend(); i++) {
316+
for (auto i = elems.rbegin(); i != elems.rend(); i++) {
315317
if (started) { // 如果多余的0已经都跳过,则输出
316-
result << std::setw(4) << std::setfill('0') << *i;
318+
result << std::setw(RADIX_LEN) << std::setfill('0') << *i;
317319
} else {
318320
result << *i;
319321
started = true; // 碰到第一个非0的值,就说明多余的0已经都跳过
@@ -331,12 +333,12 @@ \subsubsection{代码}
331333
* @return 大整数
332334
*/
333335
static BigInt multiply(const BigInt &x, const BigInt &y) {
334-
vector<int> z(x.n.size() + y.n.size() + 1, 0);
336+
vector<int64_t> z(x.elems.size() + y.elems.size() + 1, 0);
335337

336-
for (size_t i = 0; i < y.n.size(); i++) {
337-
for (size_t j = 0; j < x.n.size(); j++) { // 用y[i]去乘以x的各位
338+
for (size_t i = 0; i < y.elems.size(); i++) {
339+
for (size_t j = 0; j < x.elems.size(); j++) { // 用y[i]去乘以x的各位
338340
// 两数第i, j位相乘,累加到结果的第i+j位
339-
z[i + j] += y.n[i] * x.n[j];
341+
z[i + j] += y.elems[i] * x.elems[j];
340342

341343
if (z[i + j] >= BIGINT_RADIX) { // 看是否要进位
342344
z[i + j + 1] += z[i + j] / BIGINT_RADIX; // 进位
@@ -349,12 +351,15 @@ \subsubsection{代码}
349351
}
350352

351353
private:
352-
/** 一个数组元素表示4个十进制位,即数组是万进制的 */
353-
const static int BIGINT_RADIX = 10000;
354-
const static int RADIX_LEN = 4;
354+
typedef long long int64_t;
355+
/** 一个数组元素对应9个十进制位,即数组是亿进制的
356+
* 因为 1000000000 * 1000000000 没有超过 2^63-1
357+
*/
358+
const static int BIGINT_RADIX = 1000000000;
359+
const static int RADIX_LEN = 9;
355360
/** 万进制整数. */
356-
vector<int> n;
357-
BigInt(const vector<int> num) : n(num) {}
361+
vector<int64_t> elems;
362+
BigInt(const vector<int64_t> num) : elems(num) {}
358363
};
359364

360365

0 commit comments

Comments
 (0)