g0001_0100.s0067_add_binary.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0067_add_binary;
// #Easy #String #Math #Bit_Manipulation #Simulation
// #2022_02_19_Time_3_ms_(67.14%)_Space_42.4_MB_(14.42%)
public class Solution {
public String addBinary(String a, String b) {
char[] aArray = a.toCharArray();
char[] bArray = b.toCharArray();
StringBuilder sb = new StringBuilder();
int i = aArray.length - 1;
int j = bArray.length - 1;
int carry = 0;
while (i >= 0 || j >= 0) {
int sum = (i >= 0 ? aArray[i] - '0' : 0) + (j >= 0 ? bArray[j] - '0' : 0) + carry;
sb.append(sum % 2);
carry = sum / 2;
if (i >= 0) {
i--;
}
if (j >= 0) {
j--;
}
}
if (carry != 0) {
sb.append(carry);
}
return sb.reverse().toString();
}
}