任意長度的高精度大整數加法

來源:互聯網
上載者:User

方法:這裡用了資料結構棧,實際上棧更方便實現高精度加法。

步驟:1、第一個資料加數按輸入順序(高位到低位)入棧1。此時棧頂為最低位

            2、第二個資料加數按輸入順序(高位到低位)入棧2。此時棧頂為最低位

            3、將棧1、棧2均pop出棧頂做加法,並考慮進位,結果入棧3,這時棧3正好是低位入棧。

            4、處理多餘的棧1、棧2。

            5、直接pop出棧3,即正好的從高位到低位的結果。

 完整的實現代碼如下:

#include "iostream"#include "stack"using namespace std;stack<int>s1;stack<int>s2;stack<int>s3;char c1[100];char c2[100];int main(void){printf("請輸入第一個加數:");cin>>c1;printf("請輸入第二個加數:");cin>>c2;int len1=strlen(c1);int len2=strlen(c2);for(int i=0;i<len1;i++){s1.push(c1[i]-'0');            //按輸入順序(高位到低位)入棧1,此時棧頂為最低位}for(int i=0;i<len2;i++){s2.push(c2[i]-'0');            //按輸入順序(高位到低位)入棧2,此時棧頂為最低位}int tmp=0;while(!s1.empty() && !s2.empty()){tmp += s1.top()+s2.top();   // 將棧1、棧2均pop出棧頂做加法,並考慮進位,結果入棧3,這時棧3正好是低位入棧s1.pop();s2.pop();s3.push(tmp%10);tmp = tmp/10;}while(!s1.empty())   //處理多餘的棧1{tmp += s1.top();s1.pop();s3.push(tmp%10);tmp = tmp/10;}while(!s2.empty())   //處理多餘的棧2{tmp += s2.top();s2.pop();s3.push(tmp%10);tmp = tmp/10;}if(tmp)        //處理多餘的進位{s3.push(tmp);}printf("兩個數相加的結果為:");while(!s3.empty())    //直接pop出棧3,即正好的從高位到低位的結果{cout<<s3.top();s3.pop();}cout<<endl;system("pause");return 0;}

運行如下:

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.