Leetcode first _ Add Binary

Source: Internet
Author: User

Binary addition is essentially a big integer addition. My roommates have taught me a good way to add big integers. They first save the result with an int array and add the two numbers to the corresponding positions, after all are added, the carry problem is processed in a unified manner. This method also applies to multiplication of large integers.

There is nothing special about this question. Pay attention to the wrong carry. In addition, you don't have to worry about it. You can determine which one is longer at the beginning and exchange it. The code is much simpler.

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;    }};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.