Given binary strings, return their sum (also a binary string).
For example,
A = "11"
b = "1"
Return "100".
There are 3 ways to solve a problem: carry, which is longer, how to return.
1, as for the carry is the use of charat (i)-' 0 ' to obtain the value of each bit, and then use in addition to 2 and modulo 2 to operate, the rounding can be passed through the loop.
2, as for the longer, and the combination of the group is similar, first look at the existence of two, and then see whether there is any surplus.
3, the return value uses StringBuilder to splice, but finally needs to add the carry in, then reverses, turns the string.
public class Solution {public String addbinary (string A, string b) {if (a==null| |
A.length () ==0) return B; if (b==null| |
B.length () ==0) return A;
int I=a.length ()-1;
int J=b.length ()-1;
int carry=0;
StringBuilder r=new StringBuilder ();
while (i>=0&&j>=0) {int re= (int) (A.charat (i)-' 0 ' +b.charat (j)-' 0 ') +carry;
CARRY=RE/2;
re=re%2;
R.append (re);
i--;
j--;
} while (i>=0) {int re= (int) (A.charat (i)-' 0 ') +carry;
CARRY=RE/2;
re=re%2;
R.append (re);
i--;
} while (j>=0) {int re= (int) (B.charat (j)-' 0 ') +carry;
CARRY=RE/2;
re=re%2;
R.append (re);
j--;
} if (carry>0) {r.append (carry);
} return R.reverse (). toString (); }
}
The code is a bit long: compress it and transfer it from someone else's code:
Class Solution {public
string addbinary (String A, string b) {
int c = 0;
StringBuilder sb = new StringBuilder ();
for (int i = A.length ()-1, J = b.length ()-1; I >= 0 | | J >= 0;) {
if (i >= 0) c + = A.charat (i--)-' 0 ';
if (J >= 0) C + = B.charat (j--)-' 0 ';
Sb.insert (0, (char) ((c% 2) + ' 0 '));
C/= 2;
}
if (c = = 1) sb.insert (0, "1");
return sb.tostring ();
}
}