大数乘法——POJ2389

来源:互联网 发布:八爪鱼采集器的源码 编辑:程序博客网 时间:2024/06/05 08:47

POJ2389


/************************************************************算法原理:相乘时错位相加,具体见图。Notice:1)翻转数组的方法①利用栈②对称位置互换2)也可以从后向前保存字符,即result[t] = temp[t] % 10 + '0' ;   然后从前向后找第一个不为零的地方,即有效的起始位置3)注意处理进位情况4)初始化为零,利用它字符串截断的特性************************************************************/#include <stdio.h>#include<iostream>using namespace std;const int Length = 100;void stringReverse(char *s){for (int i = 0, j = 0, temp = 0,mid = (strlen(s) - 1) / 2; i <=mid; i++){j = strlen(s) - 1 - i;temp = s[i];s[i] = s[j];s[j] = temp;}}void stringMultiply(char* lhs, char* rhs, char* result){int temp[Length] = { 0 };//注意int型变量int s, t, i, j, head, value = 0, k = Length - 1;//从后往前加,避免翻转; -1 防止越界for (i = strlen(lhs) - 1; i >= 0; i--){head = k--;//保证错开一位相加value = lhs[i] - '0';for (j = strlen(rhs) - 1; j >= 0; j--)temp[head--] += value*(rhs[j] - '0');//图中相加的一步for (t = Length - 1, s = 0; t > head; t--)//注意这里的条件是t>head ,不取等号因为上面是head--{result[s++] = temp[t] % 10 + '0' ;//result是反的temp[t - 1] += temp[t] / 10;}if (temp[t] > 0)result[s++] = temp[t]+ '0';//处理进位情况stringReverse(result);}int main(){char test[100] = { 0 }, a[40] = {0}; char b[40] = { 0 };scanf("%s %s", a, b);stringMultiply(a, b, test);printf("%s\n", test);}


0 0
原创粉丝点击