演算法導論 習題2.1-4

來源:互聯網
上載者:User

有兩個各存放在數組A和B中的n位二進位整數,考慮它們的相加問題。兩個整數的和以二進位形式存放在具有(n+1)個元素的數組C中。請給出這個問題的形式化描述,並寫出虛擬碼。

以下是我寫的C++代碼,如有錯誤請指出

#include "stdafx.h"#include<iostream>#include<string>#define n 20using namespace std;void add(int a[],int b[],int c[]){for(int i=0;i<n-1;i++){c[i]+=(a[i]+b[i]);if(c[i]>=2){c[i+1]+=c[i]/2;c[i]=c[i]%2;}}c[n-1]+=(a[n-1]+b[n-1]);//處理最高位if(c[n-1]>=2){c[n]+=c[n-1]/2;c[n-1]=c[n-1]%2;}}int _tmain(int argc, _TCHAR* argv[]){int A[n];int B[n];int C[n+1];memset(C,0,sizeof(int)*(n+1));for(int i=0;i<n;i++)A[i]=rand()%2;for(int i=0;i<n;i++)B[i]=rand()%2;add(A,B,C);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.