c# 實現二進制加法

//兩個任意位數的二進制整數加起來的問題,兩個整數分別存儲在兩個數組中
       static public int[] add_2(ref int[] a, ref int[] b) {
           int reLength = Math.Max(a.Length, b.Length);
           int[] re=new int[reLength+1];//返回計算結果的數組
           int carry=0;//進位數
           int temp;
           int i, j, k;
           for( i=a.Length-1,j=b.Length-1,k=reLength;i>=0&&j>=0;i--,j--,k--){
               temp = a[i] + b[j]+carry;
               if(temp>=2){
                   carry=1;
                   re[k]=temp-2;
               }else{
                   re[k] = temp;
                   carry = 0;
               }
           }
           /*
            * 分爲三種情況
            * 1)兩個數位數相同,都被加完,re的最高位加carry就可以;
            * 2)a被加完,b還沒有加完;
            * 3)與2)情況相反。
            */
           if (i >= 0)
           {
               while (i >= 0) {
                   temp = a[i] + carry;
                   re[k] = (temp == 2) ? 0 : temp;
                   carry = (temp == 2) ? 1 : 0;
                   i--;
                   k--;
               }
           }
           else if(j>=0)
           {
               while (j >= 0)
               {
                   temp = b[j] + carry;
                   re[k] = (temp == 2) ? 0 : temp;
                   carry = (temp == 2) ? 1 : 0;
                   j--;
                   k--;
               }
           }
           re[0] = re[0] + carry;


           return re;
       }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章