【一直蒟蒻的刷題歷程】 【洛谷】 高精度乘法

洛谷 / 題目列表 / 題目詳情

P1303 A*B Problem

題目描述

求兩數的積。

輸入格式

兩行,兩個整數。

輸出格式

一行一個整數表示乘積。

輸入輸出樣例

輸入 #1

1
2

輸出 #1

2

說明/提示

每個數字不超過 102000 ,需用高精。


思路:

模擬手算過程,先把兩個字符串都倒置存入數組中,例如
368
432

存入數組
863
234
————————
16 12   6
      24 18   9
            32 24 12
—————————
16   36 56 33 12
————————
6 7 9 8 5 1 (進位代碼下面)


逆序輸出:158976

然後進位

for(int i=1;i<len;i++)
  {
  	if(ans[i]>=10)
  	{
  		ans[i+1] += ans[i]/10;
  		ans[i]%=10;
	}
  }

代碼:

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <set>
#include <map>
using namespace std;  
int main()
{
  string s1,s2;
  int a[3100]={0},b[3000]={0},ans[4000]={0};
  //ans的數組要開大點,應該要99*99有四位數,999*999有六位數
  //所以最好開到2000*2
  cin>>s1>>s2;
  int len1=s1.length(),len2=s2.length();
  int c=1;
  for(int i=len1-1;i>=0;i--)  //s1存入數組 
     a[c++]=s1[i]-'0';
  c=1;
  for(int j=len2-1;j>=0;j--) //s2存入數組 
     b[c++]=s2[j]-'0';
     
  for(int i=1;i<=len1;i++)  //模擬手算
  	for(int j=1;j<=len2;j++)
  		ans[i+j-1] += a[i]*b[j]; 
  
  int len=len1+len2;
  for(int i=1;i<len;i++) //進位
  {
  	if(ans[i]>=10)
  	{
  		ans[i+1] += ans[i]/10;
  		ans[i]%=10;
	}
  }
  
  for(int i=len;i>=1;i--) //去除前面無效的0
  {
  	if(ans[i]==0 && len>1) len--; //保證len有一位,比如0*任何數
  	else break;
  }
  for(int i=len;i>=1;i--) //倒序輸出
   cout<<ans[i];
  return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章