Add Binary

描述

Given two binary strings, return their sum (also a binary string).

For example,

  1. a = "11"
  2. b = "1"

Return 100.

分析

代码

  1. // Add Binary
  2. // 时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public String addBinary(String a, String b) {
  5. StringBuilder result = new StringBuilder();
  6. int i = a.length() - 1;
  7. int j = b.length() - 1;
  8. int carry = 0;
  9. while(i >= 0 || j >= 0 || carry > 0) {
  10. int valueA = i < 0 ? 0 : a.charAt(i--) - '0';
  11. int valueB = j < 0 ? 0 : b.charAt(j--) - '0';
  12. int sum = valueA + valueB + carry;
  13. result.insert(0, Character.forDigit(sum % 2, 10));
  14. carry = sum / 2;
  15. }
  16. return result.toString();
  17. }
  18. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/string/add-binary.html