您的位置:首页 > 其它

大数乘法:忽略特殊情况(比如0等简单的情况)

2017-05-31 10:28 267 查看
//题目:求两个大于2的31次方的整数的乘积,都是32位整数 
1 #include<iostream>
 2 using namespace std;
 3 void print_c(string c)
 4 {
 5     bool first0 = false;
 6     int i;
 7     for(i = 0;i<c.length();i++)
 8     {
 9         if(c[i] != '0')
10         {
11             first0 = true;
12             break;
13         }
14     }
15     while(first0 == true && c[i] != '\0')
16     {
17             cout << c[i] ;
18             i++;
19     }
20 }
21 int main()
22 {
23     string a,b,c;
24     cin >> a >> b;
25     int i,j,k,a_j,b_i;
26     for(i = 0;i<a.length()+b.length();i++)
27         c += '0';
28     int up = 0,loop = 0,clen = c.length();
29     for(i = b.length()-1;i>=0;i--)
30     {
31         b_i = b[i]-'0';
32         int temp;
33         k = 0;
34         for(j = a.length()-1;j>=0;j--)
35         {
36             a_j = a[j] - '0';
37             temp = (c[clen-1-k-loop]-'0')+up+(a_j*b_i-(a_j*b_i/10)*10);//计算当前的数字
38             if(temp >=10)
39             {
40                 c[clen-1-k-loop] = (temp - temp/10*10) + '0';
41                 up = temp/10 + (a_j*b_i/10);//如果>10的话,需要计算的是temp的进位和乘积运算的进位
42             }
43             else
44             {
45                 c[clen-1-k-loop] = temp + '0';
46                 up = (a_j*b_i/10);
47             }
48             k++;
49         }
50         if(up != 0)
51         {
52             c[clen-1-k-loop] = up+'0';
53             up = 0;
54         }
55         loop ++;
56     }
57     print_c(c);
58     cout << a<<"*"<<b << "is: " << c << endl;
59     system("pause");
60     
61     return 0;
62 }

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: