P1303 A*B Problem
题解
思路就是模拟竖式乘法,但注意乘的时候会有位偏移,我用一个count来处理这个问题。题目中说的是整数,写的时候就把负数情况也考虑了进去,但最后貌似是没有负数的。此外需要注意的就是0时的情况,只输出一个0,需要想办法判断一下。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
struct Num {
int num[5001];
int start;
int len;
bool zf; //正负性,正为true,负为false;
};
typedef struct Num NUM;
void getNum(NUM& n)
{
char str[5001] = { 0 };
scanf("%s", str);
int ptr = 5000; //num的尾部
if (str[0] == '-')
{
n.zf = false;
n.len = strlen(str)-1; //数字长度
for (int i = strlen(str) - 1; i >= 1; i--)
{
n.num[ptr] = str[i] - '0';
ptr--;
}
}
else
{
n.zf = true;;
n.len = strlen(str); //数字长度
for (int i = strlen(str) - 1; i >= 0; i--)
{
n.num[ptr] = str[i] - '0';
ptr--;
}
}
n.start = 5000;
}
void NumInit(NUM& n)
{
for (int i = 0; i <= 5000; i++)
{
n.num[i] = 0;
}
}
NUM plusNum(NUM& n1, NUM& n2)
{
int len = n1.len > n2.len ? n1.len : n2.len;
int tmp = 0;
NUM ans;
ans.len = 0;
ans.start = 5000;
for (int i = 0; i <= 5000; i++)
{
ans.num[i] = 0;
}
for (int i = 0; i < len; i++)
{
int loc = 5000 - i;
if (tmp == 1)
{
ans.num[loc] += 1;
tmp = 0;
}
ans.num[loc] += n1.num[loc] + n2.num[loc];
if (ans.num[loc] >= 10)
{
ans.num[loc] -= 10;
tmp = 1;
}
ans.len++;
}
if (tmp == 1)
{
ans.len++;
ans.num[ans.start - ans.len + 1] = 1;
tmp = 0;
}
return ans;
}
NUM multiplication(NUM n1, NUM n2)
{
NUM ans;
NumInit(ans);
int count = 0;
for (int i = n2.start; i >= n2.start - n2.len+1; i--)
{
NUM mid;
NumInit(mid);
int ptr = 5000 - count;
count++;//位偏移
mid.len = 0;
mid.start = 5000;
int forwardNum = 0;
bool flag = false;
for (int j = n1.start; j >= n1.start - n1.len + 1; j--)
{
mid.num[ptr] += forwardNum; //先加进位
forwardNum = 0; //进位清空
int tmp = n1.num[j] * n2.num[i]; //计算当前位
if (tmp != 0)
flag = true;
forwardNum = tmp / 10; //计算进位
mid.num[ptr] += tmp % 10;
if (mid.num[ptr] >= 10)
{
forwardNum += 1;
mid.num[ptr] -= 10;
}
ptr--;
}
if (forwardNum != 0)
{
mid.num[ptr] += forwardNum;
forwardNum = 0;
ptr--;
}
if(flag)
mid.len = 5000 - ptr;
else
mid.len = 1;
ans = plusNum(ans, mid);
}
return ans;
}
int main()
{
NUM n1, n2;
NumInit(n1);
NumInit(n2);
getNum(n1);
getNum(n2);
//得到两个数字
NUM ans = multiplication(n1, n2);
if (n1.zf != n2.zf)
{
printf("-");
}
for (int i = ans.start - ans.len + 1; i <= ans.start; i++)
{
printf("%d", ans.num[i]);
}
printf("\n");
}