红桃J

用心写好每行完美的代码,远比写一堆更有价值

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

代码:

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 
 5 using namespace std;
 6 
 7 void swap(char &a, char &b)
 8 {
 9     char c = a;
10     a = b;
11     b = c;
12 }
13 
14 void reverse(string &s)
15 {
16     int L = s.size();
17     int i = 0;
18     while (i <= (L-1) / 2)
19     {
20         swap(s[i], s[L - i-1]);
21         i++;
22     }
23 }
24 
25 string multiply(string num1, string num2) 
26 {
27     if (num1 == "0" || num2 == "0")
28         return "0";
29     int L1 = num1.length();
30     int L2 = num2.length();
31     reverse(num1);
32     reverse(num2);
33     int *result = new int[L1+L2];
34     memset(result, 0, (L1 + L2)*sizeof(int));
35     int i, j;
36     int c;
37     for (i = 0; i <L1; i++)
38     {
39         c = 0;
40         for (j = 0; j <L2; j++)
41         {
42             int mul = (num1[i]-'0') *( num2[j]-'0');
43             int cur = mul % 10 + c + result[i + j];
44             result[i + j] = cur % 10;
45             c = cur / 10 + mul / 10;
46         }
47         if (c>0)
48             result[i + j] += c;
49     }
50     string resultS = "";
51     if (result[L1 + L2 -1] != 0)
52         resultS += (result[L1 + L2-1] + '0');
53     for (int i = L1 + L2-2; i >=0; i--)
54         resultS += (result[i] + '0');
55     return resultS;
56 }
57 
58 int main()
59 {
60     cout<<multiply("9", "9")<<endl;
61     return 0;
62 }

 

posted on 2015-06-11 23:42  红桃J  阅读(135)  评论(0编辑  收藏  举报