Given binary strings, return their sum (also a binary string).
for example,
a = " "
b = " 1 "
return "
.
Idea: binary addition, relatively simple. The code is as follows:
public class Solution {public String addbinary (String A, string b) { int len = Math.max (A.length (), b.length ());
char[] ch = new Char[len + 1];//prevent rounding int i = A.length ()-1; Int J = b.length ()-1; Do not consider rounding, all add while (I >= 0 && J >= 0) { ch[len--] = (char) (A.charat (i--) + B.charat (j--)-' 0 '); } //Only one remaining is not completed while (I >= 0) { ch[len--] = A.charat (i--); } while (J >= 0) { ch[len--] = B.charat (j--); } int k = 0;//carry //handle carry for (i = ch.length-1; I >=1; i--) { Ch[i] = (char) (k + ch[i]-' 0 '); K = CH[I]/2; Ch[i] = (char) (ch[i]%2 + ' 0 '); } Determine if there is a carry ch[0] = (char) (k > 0? k + ' 0 ': ' 0 '); Eliminate the beginning of the 0 return new String (CH). ReplaceAll ("^0", "");} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 67.ADD Binary (binary addition) ideas and methods for solving problems