1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Solution{ public: string (string a, string b) { string res = ""; int len_a = a.length(); int len_b = b.length(); int carry = 0; while(len_a > 0 || len_b > 0){ int abit = len_a > 0 ? a[len_a-1] - '0' : 0; int bbit = len_b > 0 ? b[len_b-1] - '0' : 0; int cbit = carry > 0 ? 1 : 0; res.insert(res.begin(), '0' + ((abit + bbit + cbit) & 1)); carry = (abit + bbit + cbit) / 2; len_a--; len_b--; } if(carry > 0) res.insert(res.begin(), '0' + carry); return res; } };
|
近期评论