@import url(http://m.shnenglu.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
最近在學(xué)習(xí)游戲開(kāi)發(fā),又得重新看C++鳥(niǎo),為了進(jìn)行語(yǔ)法的熟悉決定再次進(jìn)行刷oj,我刷的oj時(shí)杭電的oj。在1002題時(shí)候,卡了一下,但最終還是順利通過(guò)。
大數(shù)加法是一項(xiàng)十分十分基本的編程技能,好鳥(niǎo)不啰嗦鳥(niǎo)。
算法核心思想:1.將字符串按照權(quán)重轉(zhuǎn)換為整型數(shù)組中相應(yīng)的位(0索引對(duì)應(yīng)最低位,權(quán)重為1,是個(gè)位)。2.然后進(jìn)行按照位相加運(yùn)算。
具體代碼如下。
2 // main.cpp
3 // oj
4 //
5 // Created by sixleaves on 14-7-23.
6 // Copyright (c) 2014年 sixleaves. All rights reserved.
7 //
8
9 #include <iostream>
10 #include <string>
11 #include <cstdlib>
12 const int ArSize = 1024;
13 using namespace std;
14 char *psResult = new char[ArSize];// 分配于堆中,不是局部變量
15 char* sum(string a, string b);
16 int main(int argc, const char * argv[])
17 {
18
19 int nTestCase;
20 int i = 0;
21 cin >> nTestCase;
22 while (i < nTestCase) {
23 string a,b;
24 while (cin >> a >> b) {
25 cout << "Case " << i + 1 <<":"<< endl;
26 cout << a + " + " + b + " = "
27 <<sum(a, b) << endl;
28 if(i + 1 != nTestCase)
29 cout << endl;
30 i++;
31 break;
32 }
33 }
34 return 0;
35 }
36
37 char* sum(string a, string b) {
38 // 進(jìn)行數(shù)據(jù)的轉(zhuǎn)換,把字符串?dāng)?shù)據(jù)轉(zhuǎn)換為整數(shù)
39 // char *psResult = new char[ArSize];
// 為了提高程序速度,把這個(gè)放在了外面,不用每次都申請(qǐng)
40 int nR[ArSize] = {0}, nA[ArSize] = {0}, nB[ArSize] = {0};// 并且都初始化為0
41 int nLenA = a.length(), nLenB = b.length();
42 for(int i = 0; i < nLenA; i++) {
43 nA[i] = a[nLenA - i - 1] - '0';
44 }
45 for(int i = 0; i < nLenB; i++) {
46 nB[i] = b[nLenB - i - 1] - '0';
47 }
48 // 進(jìn)行相加運(yùn)算
49 int nLenMax = nLenA > nLenB? nLenA : nLenB;
50 for(int i = 0; i < nLenMax; i++) {
51 nR[i] += nA[i] + nB[i];
52 if(nR[i] > 9) {
53 nR[i] -= 10;
54 nR[i + 1]++;
55 }
56 }
57 // 轉(zhuǎn)換為字符串
58 if(nR[nLenMax] != 0)// 如果最后一位相加有近位,則總長(zhǎng)度加1
59 nLenMax++;
60 for(int i = 0; i < nLenMax; i++) {
61 psResult[i] = nR[nLenMax - i - 1] + '0';
62 }
63 psResult[nLenMax] = '\0';
64 return psResult;
65 }
66