[LeetCode] Add Binary

来源:互联网 发布:手机淘宝6.10旧版本 编辑:程序博客网 时间:2024/05/21 10:19

Add from tail to head

class Solution {public:    string addBinary(string a, string b) {        if(a.length()<b.length()) {            string t = a; a = b; b = t;        }        int carry = 0;        string result = a;        int i=a.length()-1, j=b.length()-1;        while(j>=0) {            int tmp = (a[i]-'0') + (b[j]-'0') + carry;            carry = tmp/2;            result[i] = tmp%2 + '0';            i--;j--;        }        while(i>=0) {            int tmp = (a[i]-'0') + carry;            carry = tmp/2;            result[i] = tmp%2 + '0';            i--;        }        if(carry==0) return result;        result = "1"+result;        return result;    }};


0 0
原创粉丝点击