f(sixleaves) = sixleaves

重剑无锋 大巧不工

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  95 随笔 :: 0 文章 :: 7 评论 :: 0 Trackbacks
@import url(http://www.cppblog.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 
posted on 2014-07-24 02:58 swp 阅读(156) 评论(0)  编辑 收藏 引用 所属分类: algorithm

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理