Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
class Solution { public: string addBinary(string a, string b) { string s; int lena = a.length() - 1; int lenb = b.length() - 1; int temp = 0; char c; while(lena >= 0 && lenb >= 0) { c = (a[lena] - '0') + (b[lenb] - '0') + temp + '0'; temp = 0; if((c - '0') >= 2) { temp = 1; c = c - 2; } s = c + s; lena--; lenb--; } while(lena >= 0) { c = (a[lena] - '0') + temp + '0'; temp = 0; if((c - '0') >= 2) { temp = 1; c = c - 2; } s = c + s; lena--; } while(lenb >= 0) { c =(b[lenb] - '0') + temp + '0'; temp = 0; if((c - '0') >= 2) { temp = 1; c = c - 2; } s = c + s; lenb--; } if(temp == 1) { s = '1' + s; } return s; } }; |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼