Skip to main content

Bit Manipulation

Leetcode - addBinary

  • TODO: solve it with bit manipulation way too
  • you can insert a int strictly into the stringbuilder. It gets converted to Integer and stringbuilder prints the integer object.
  public String addBinary(String first, String second) {
int firstI = first.length() - 1;
int secondI = second.length() - 1;
StringBuilder result = new StringBuilder();
int carry = 0;
// carry can never be more than a base
while (0 <= firstI || 0 <= secondI) {
int x = firstI < 0 ? 0 : first.charAt(firstI) - '0';
int y = secondI < 0 ? 0 : second.charAt(secondI) - '0';
int sum = x + y + carry;
carry = sum / 2;
int val = sum % 2;
result.insert(0, val);
firstI--; secondI--;
}
if (0 < carry) result.insert(0, carry);
return result.toString();
}