@import url(http://www.shnenglu.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
最近在學習游戲開發,又得重新看C++鳥,為了進行語法的熟悉決定再次進行刷oj,我刷的oj時杭電的oj。在1002題時候,卡了一下,但最終還是順利通過。
大數加法是一項十分十分基本的編程技能,好鳥不啰嗦鳥。
算法核心思想:1.將字符串按照權重轉換為整型數組中相應的位(0索引對應最低位,權重為1,是個位)。2.然后進行按照位相加運算。
具體代碼如下。
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 // 進行數據的轉換,把字符串數據轉換為整數
39 // char *psResult = new char[ArSize];
// 為了提高程序速度,把這個放在了外面,不用每次都申請
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 // 進行相加運算
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 // 轉換為字符串
58 if(nR[nLenMax] != 0)// 如果最后一位相加有近位,則總長度加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