C++實(shí)現(xiàn)大數(shù)乘法算法代碼
更新時(shí)間:2015年03月11日 11:54:23 投稿:hebedich
這篇文章主要介紹了C++實(shí)現(xiàn)大數(shù)乘法算法代碼的相關(guān)資料,需要的朋友可以參考下
C++實(shí)現(xiàn)大數(shù)乘法算法代碼
復(fù)制代碼 代碼如下:
//大數(shù)乘法算法
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
string num1,num2;
cin >> num1 >> num2;
//cout << num1.size() << " " << num2.size() << endl;
const char* n1;
const char* n2;
if (num1.size() < num2.size())
{
n1 = num2.c_str();
n2 = num1.c_str();
}
else
{
n1 = num1.c_str();
n2 = num2.c_str();
}
char* n = new char[strlen(n1)+strlen(n2)+1];
for (unsigned int i = 0; i < strlen(n1)+strlen(n2); i++)
n[i] = '0';
n[strlen(n1)+strlen(n2)]='\0';
//cout << strlen(n) << endl;
int count = 0,flag = 0;
for (int i = strlen(n1)-1; i >= 0; i--)
{
flag++;
int x1 = n1[i]-'0';
//cout << "n1["<< i << "]為:" << x1 << endl;
char carry = '0';
for (int j = strlen(n2)-1; j >= 0; j--)
{
int x2 = n2[j]-'0';
//cout << "n2["<< j << "]為:" << x2 << endl;
//cout << "當(dāng)前位未改變前值為: " << n[count] << endl;
int sum = x1*x2 + (carry-'0') + n[count]-'0';
//cout << "sum is " << sum << endl;
n[count++] = (sum % 10)+'0';
carry = (sum / 10)+'0';
//cout << "當(dāng)前位的值為: " << n[count-1] << endl;
//cout << "carry的值為:" << carry << endl;
}
if (carry != '0')
{
n[count] = carry;
count = flag;
//cout << "當(dāng)前位的值為: " << n[count] << endl;
}
else
count = flag;
}
for (int i = strlen(n)-1; i >= 0; i--)
{
if ((i == strlen(n)-1)&&(n[i] == '0'))
continue;
cout << n[i];
}
cout << endl;
delete[]n;
system("pause");
return 0;
}
以上就是本文所述的全部?jī)?nèi)容了,希望大家能夠喜歡。
相關(guān)文章
c++ vector模擬實(shí)現(xiàn)的全過(guò)程
這篇文章主要給大家介紹了關(guān)于c++ vector的模擬實(shí)現(xiàn)過(guò)程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04C++多重繼承引發(fā)的重復(fù)調(diào)用問(wèn)題與解決方法
這篇文章主要介紹了C++多重繼承引發(fā)的重復(fù)調(diào)用問(wèn)題與解決方法,結(jié)合具體實(shí)例形式分析了C++多重調(diào)用中的重復(fù)調(diào)用問(wèn)題及相應(yīng)的解決方法,需要的朋友可以參考下2018-05-05C語(yǔ)言求兩個(gè)正整數(shù)的最大公約數(shù)示例代碼
在C語(yǔ)言中求兩個(gè)數(shù)的最大公約數(shù)是學(xué)習(xí)循環(huán)語(yǔ)句的非常經(jīng)典的問(wèn)題,下面這篇文章主要給大家介紹了關(guān)于C語(yǔ)言求兩個(gè)正整數(shù)的最大公約數(shù)的相關(guān)資料,需要的朋友可以參考下2021-12-12Visual Studio Code 配置C、C++環(huán)境/編譯并運(yùn)行的流程分析
這篇文章主要介紹了Visual Studio Code 配置C、C++環(huán)境/編譯并運(yùn)行的流程分析,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-05-05C語(yǔ)言實(shí)現(xiàn)將字符串轉(zhuǎn)換為數(shù)字的方法
這篇文章主要介紹了C語(yǔ)言實(shí)現(xiàn)將字符串轉(zhuǎn)換為數(shù)字的方法,涉及系統(tǒng)函數(shù)atoi()函數(shù)的使用技巧,需要的朋友可以參考下2014-12-12