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);
}