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;
}
以上就是本文所述的全部內(nèi)容了,希望大家能夠喜歡。
相關(guān)文章
C++多重繼承引發(fā)的重復(fù)調(diào)用問題與解決方法
這篇文章主要介紹了C++多重繼承引發(fā)的重復(fù)調(diào)用問題與解決方法,結(jié)合具體實(shí)例形式分析了C++多重調(diào)用中的重復(fù)調(diào)用問題及相應(yīng)的解決方法,需要的朋友可以參考下2018-05-05
C語言壓縮文件和用MD5算法校驗(yàn)文件完整性的實(shí)例教程
這篇文章主要介紹了C語言壓縮文件和用MD5算法校驗(yàn)文件完整性的實(shí)例教程,這里演示了Windows下將文件壓縮為7z格式以及MD5檢驗(yàn)文件和密碼的方法,需要的朋友可以參考下2016-04-04
用c語言實(shí)現(xiàn)HUP信號(hào)重啟進(jìn)程的方法
本篇文章是對(duì)使用c語言實(shí)現(xiàn)HUP信號(hào)重啟進(jìn)程的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
詳解C++ 多態(tài)的兩種形式(靜態(tài)、動(dòng)態(tài))
這篇文章主要介紹了C++ 多態(tài)的兩種形式,幫助大家更好的理解和學(xué)習(xí)c++,感興趣的朋友可以了解下2020-08-08
C++標(biāo)準(zhǔn)模板庫string類的介紹與使用講解
今天小編就為大家分享一篇關(guān)于C++標(biāo)準(zhǔn)模板庫string類的介紹與使用講解,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2018-12-12
Cocos2d-x學(xué)習(xí)入門之HelloWorld程序
這篇文章主要介紹了Cocos2d-x學(xué)習(xí)入門之HelloWorld程序,是學(xué)習(xí)Cocos2d-x的入門程序,其重要性不言而喻,需要的朋友可以參考下2014-08-08
QT網(wǎng)絡(luò)通信TCP客戶端實(shí)現(xiàn)詳解
這篇文章主要為大家詳細(xì)介紹了QT網(wǎng)絡(luò)通信TCP客戶端實(shí)現(xiàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08

