信息学奥赛一本通 1307:【例1.3】高精度乘法 | 1174:大整数乘法 | OpenJudge NOI 1.13 09:大整数乘法
生活随笔
收集整理的這篇文章主要介紹了
信息学奥赛一本通 1307:【例1.3】高精度乘法 | 1174:大整数乘法 | OpenJudge NOI 1.13 09:大整数乘法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【題目鏈接】
ybt 1307:【例1.3】高精度乘法
ybt 1174:大整數乘法
OpenJudge NOI 1.13 09:大整數乘法
【題目考點】
1. 高精度
考察:高精乘高精
高精度計算講解
【解題思路】
ybt 1307:【例1.3】高精度乘法:該題中是兩個100位的數字相乘,結果可能達到200位。
ybt 1174 / OpenJudge 1.13 09 大整數乘法:該題中是兩個200位的數字相乘,結果可能達到400位。
代碼中將數字數組長度N設為500,即可滿足以上兩題。
【題解代碼】
解法1:使用數組與函數
#include <bits/stdc++.h> using namespace std; #define N 505 void Multiply(int a[], int b[], int r[])//高精乘高精 {int i;for(i = 1; i <= a[0]; ++i){int c = 0;for(int j = 1; j <= b[0]; ++j){r[i+j-1] += a[i]*b[j] + c;c = r[i+j-1] / 10;r[i+j-1] %= 10;}r[i+b[0]] += c;}i = a[0] + b[0];//確定數字位數 while(r[i] == 0 && i > 1)i--;r[0] = i; } void toNum(char s[], int a[]) {a[0] = strlen(s);for(int i = 1; i <= a[0]; ++i)a[i] = s[a[0] - i] - '0'; } void showNum(int a[]) {for(int i = a[0]; i >= 1; --i)cout << a[i]; } int main() {int a[N] = {}, b[N] = {}, r[N] = {};char s[N];cin >> s;toNum(s, a);cin >> s;toNum(s, b);Multiply(a, b, r);showNum(r);return 0; }解法2:使用高精度數字類
#include<bits/stdc++.h> using namespace std; #define N 505 class HPN { private:int a[N]; public: HPN(){memset(a, 0, sizeof(a));}HPN(char s[]){memset(a, 0, sizeof(a));a[0] = strlen(s);for(int i = 1; i <= a[0]; ++i)a[i] = s[a[0] - i] - '0';}int& operator [] (int i){return a[i];}void setLen(int i)//確定數字位數{while(a[i] == 0 && i > 1)i--;a[0] = i;}HPN operator * (HPN &b){HPN r;for(int i = 1; i <= a[0]; ++i){int c = 0;for(int j = 1; j <= b[0]; ++j){r[i+j-1] += a[i]*b[j] + c;c = r[i+j-1] / 10;r[i+j-1] %= 10;}r[i+b[0]] += c;}r.setLen(a[0] + b[0]);return r; }void show(){for(int i = a[0]; i >= 1; --i)cout << a[i];} }; int main() {char s1[N], s2[N];cin >> s1 >> s2;HPN a(s1), b(s2), r;r = a*b;r.show();return 0; }總結
以上是生活随笔為你收集整理的信息学奥赛一本通 1307:【例1.3】高精度乘法 | 1174:大整数乘法 | OpenJudge NOI 1.13 09:大整数乘法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html暂停计时器,JS实现可暂停秒表计
- 下一篇: java字符串去掉一头一尾_快学Scal