leetcode第一刷_Add Binary

來源:互聯網
上載者:User

二進位相加,本質上就是大整數加法,有關大整數加法我的舍友教過我一個很好的方法,先用一個int數組儲存結果,將兩個數對應位置相加,全部加完後,再統一處理進位的問題。這個方法同樣適用於大整數的乘法。

這個題沒什麼特別的,注意一下進位別搞錯了就行了,還有其實不用像我寫的這麼麻煩,可以一開始先判斷哪個更長一些,交換一下。代碼會簡潔很多。

class Solution {public:    string addBinary(string a, string b) {        int l1 = a.length(), l2 = b.length();        string c(max(l1, l2)+1, '0');        int i1 = l1-1, i2 = l2-1, ch=0, k = max(l1, l2);        while(i1>=0&&i2>=0){            if(a[i1] == '1' && b[i2] == '1'){                c[k--] = ch+'0';                ch = 1;            }else if(a[i1]=='1'||b[i2]=='1'){                if(ch){                    c[k--] = '0';                }else{                    c[k--] = '1';                }            }else{                c[k--] = '0'+ch;                ch = 0;            }            i1--; i2--;        }        while(i1>=0){            if(ch){                if(a[i1] == '1'){                    c[k--] = '0';                    ch = 1;                }else{                    c[k--] = '1';                    ch = 0;                }            }else{                c[k--] = a[i1];            }            i1--;        }        while(i2>=0){            if(ch){                if(b[i2] == '1'){                    c[k--] = '0';                    ch = 1;                }else{                    c[k--] = '1';                    ch = 0;                }            }else{                c[k--] = b[i2];            }            i2--;        }        if(ch)            c[0] = '1';        if(c[0] == '0')            c = c.substr(1, c.length()-1);        return c;    }};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.