=================================版权声明=================================

版权声明:本文为博主原创文章 未经许可不得转载 

请通过右侧公告中的“联系邮箱(wlsandwho@foxmail.com)”联系我

未经作者授权勿用于学术性引用。

未经作者授权勿用于商业出版、商业印刷、商业引用以及其他商业用途。                   

 

本文不定期修正完善,为保证内容正确,建议移步原文处阅读。                                                               <--------总有一天我要自己做一个模板干掉这只土豆

本文链接:http://www.cnblogs.com/wlsandwho/p/4673243.html

耻辱墙:http://www.cnblogs.com/wlsandwho/p/4206472.html

=======================================================================

这个是初版

 1 #include "stdafx.h"
 2 
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 int _tmain(int argc, _TCHAR* argv[])
 8 {
 9     int a[5]={0,1,1,1,1};
10     int b[5]={1,0,1,1,1};
11     int c[6]={0,0,0,0,0,0};
12 
13     for (int i=4,t=0,s;i>=0;i--)
14     {
15         cout<<"a["<<i<<"]="<<a[i]<<endl;
16         cout<<"b["<<i<<"]="<<b[i]<<endl;
17         s=a[i]+b[i]+t;
18         cout<<"s="<<s<<endl;
19         if (s>=2)
20         {
21             t=1;
22             c[i+1]=s%2;
23         }
24         else
25         {
26             t=0;
27             c[i+1]=s;
28         }
29         
30         cout<<"t="<<t<<endl;
31         
32         if (i==0)
33         {
34             c[i]=t;
35         }
36 
37         cout<<"c["<<i+1<<"]="<<c[i+1]<<endl;
38         cout<<endl;
39     }
40 
41     for (int i=0;i<=5;i++)
42     {
43         cout<<c[i];
44     }
45     cout<<endl;
46 
47     return 0;
48 }

稍微改改便于阅读

 1 #include "stdafx.h"
 2 
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 int AddPos(int nA,int nB,int& nOverflow)
 8 {
 9     static int snOverflow=0;
10 
11     int nSum;
12 
13     nSum=nA+nB+snOverflow;
14     
15     if (nSum>=2)
16     {
17         nOverflow=snOverflow=1;
18 
19         return nSum%2;
20     }
21     else
22     {
23         nOverflow=snOverflow=0;
24 
25         return nSum;
26     }
27 }
28 
29 bool AddBinaryArray(int nArr1[],int nL1,int nArr2[],int nL2,int nArr3[],int nL3)
30 {
31     if (nL3<nL1 || nL3<nL2 || nL1!=nL2)
32     {
33         return false;
34     }
35 
36     int nOverflow=0;
37     int i=nL1-1;
38     while (i>=0)
39     {
40         nArr3[i+1]=AddPos(nArr1[i],nArr2[i],nOverflow);
41 
42         --i;
43     }
44 
45     nArr3[0]=nOverflow;
46 
47     return true;
48 }
49 
50 int _tmain(int argc, _TCHAR* argv[])
51 {
52     cout<<"The code written by WLS"<<endl;
53 
54     int nArray1[5]={0,1,1,1,1};
55     int nArray2[5]={1,0,1,1,1};
56     int nArray3[6]={0,0,0,0,0,0};
57 
58     bool bRet=AddBinaryArray(nArray1,5,nArray2,5,nArray3,6);
59     for (int i=0;i<=5;i++)
60     {
61         cout<<nArray3[i];
62     }
63     cout<<endl;
64 
65     return 0;
66 }