[LeetCode] Add Binary
Add Binary
Given two binary strings, return their sum (also a binary string ).
For example,
A ="11"
B ="1"
Return"100".
Solution:
Returns the result of adding the binary representation of two strings. Remember that regular strings and string variables can be added, but strings cannot be added with numbers, and characters cannot be added with strings.
class Solution {public: string addBinary(string a, string b) { int len1=a.length(); int len2=b.length(); int carry=0; string result=""; int i=len1-1, j=len2-1; while(i>=0&&j>=0){ int r = (a[i]-'0') + (b[j]-'0') + carry; result = (r%2==0 ? "0": "1") + result; carry = r/2; i--; j--; } while(i>=0){ int r = (a[i]-'0') + carry; result = (r%2==0 ? "0": "1") + result; carry = r/2; i--; } while(j>=0){ int r = (b[j]-'0') + carry; result = (r%2==0 ? "0": "1") + result; carry = r/2; j--; } if(carry>0){ result = "1" + result; } return result; }};