国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++實現大整數乘法(字符串乘法)

2020-01-26 13:24:38
字體:
來源:轉載
供稿:網友

本文實例為大家分享了C++實現大整數乘法的具體代碼,供大家參考,具體內容如下

#include<iostream>#include<algorithm>#include<string>using namespace std; string add(string a,string b){ if(a.length()==0) return b; if(b.length()==0) return a; a.length()<b.length()?a.swap(b):a.length();  reverse(a.begin(),a.end()); reverse(b.begin(),b.end()); int flag=0; for(int i=0;i<a.length();i++) { int aInt=a[i]-'0'; int bInt=0; if(i<b.length())  bInt=b[i]-'0'; int result=aInt+bInt+flag; a[i]=result%10+'0'; flag=result/10; } if(flag!=0) { a=a+(char)(flag+'0'); } reverse(a.begin(),a.end()); return a;}string multiply(std::string strMultiplierA,char x){ int b=x-'0'; int flag=0; for(int i=strMultiplierA.length()-1;i>=0;i--) { int a=strMultiplierA[i]-'0'; int result=a*b+flag; strMultiplierA[i]=result%10+'0'; flag=result/10; } if(flag!=0) strMultiplierA=(char)(flag+'0')+strMultiplierA; while(strMultiplierA.length()>1&&strMultiplierA[0]=='0') strMultiplierA=strMultiplierA.substr(1,strMultiplierA.length()); return strMultiplierA;} /***************************************************************************** Prototype  : multiply Description : 兩個任意長度的長整數相乘, 輸出結果 Input Param :         const std::string strMultiplierA 乘數A        const std::string strMultiplierB 乘數B Output    :         std::string strRst      乘法結果 Return Value :         int            0 正確                      -1 異常*****************************************************************************/int multiply (const std::string strMultiplierA,const std::string strMultiplierB, std::string &strRst) {   /* 在這里實現功能 */  if(strMultiplierA.length()<=0||strMultiplierB.length()<=0) return -1; bool flag=false;//false"+" true"-" string strA=strMultiplierA,strB=strMultiplierB; if(strMultiplierA[0]=='-') { flag=~flag; strA=strMultiplierA.substr(1,strMultiplierA.length()); } if(strMultiplierB[0]=='-') { flag==true?flag=false:flag=true; strB=strMultiplierB.substr(1,strMultiplierB.length()); }  for(int i=strB.length()-1;i>=0;i--) { string result=multiply(strA,strB[i]); int j=i; while(++j<strB.length())  result=result+"0"; // while(result.length()>1&&result[0]=='0') // result=result.substr(1,result.length()); strRst=add(strRst,result); } while(strRst.length()>1&&strRst[0]=='0') strRst=strRst.substr(1,strRst.length()); if(flag==true&&strRst!="0") strRst='-'+strRst;  return 0;} int main(){ std::string strResult = "";  multiply("-5489324", "0", strResult);  cout<<strResult<<endl;}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 双流县| 通榆县| 方山县| 南部县| 米林县| 湖南省| 淄博市| 班玛县| 正阳县| 屏东市| 神池县| 临城县| 报价| 稻城县| 武宣县| 常德市| 安溪县| 巴彦淖尔市| 广汉市| 蒙阴县| 厦门市| 加查县| 邵武市| 黄平县| 宜兰县| 涟水县| 沁阳市| 贵港市| 湾仔区| 承德县| 昭通市| 城步| 司法| 曲周县| 龙泉市| 镇安县| 大兴区| 清水县| 德昌县| 普兰县| 盈江县|