ADD Binary
Given binary strings, return their sum (also a binary string).
For example,
A ="11"
b ="1"
Return "100"
.
Problem Solving Ideas:
The test instructions is added to the binary represented by two strings, and the result is obtained. Remember that constant strings and string variables can be added, but strings cannot be added to numbers, and characters cannot be added to a string.
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;} ;
[Leetcode] Add Binary