LeetCode 67. Add Binary

原题链接在这里: https://leetcode.com/problems/add-binary/

题目:

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

For example,
a = "11"
b = "1"
Return "100".

题解:

Have sum = current pointing value of a + current pointing value of b + carry.

If current point value is out of index bound, then use 0.

Time Complexity: O(max(a.length(), b.length())).

Space O(max(a.length(), b.length())).

AC Java: 

 1 class Solution {
 2     public String addBinary(String a, String b) {
 3         int len1 = a.length();
 4         int len2 = b.length();
 5         int i = len1-1;
 6         int j = len2-1;
 7         int carry = 0;
 8         StringBuilder sb = new StringBuilder();
 9         while(i>=0 || j>=0 || carry >0){
10             carry += i>=0 ? a.charAt(i)-'0' : 0;
11             carry += j>=0 ? b.charAt(j)-'0' : 0;
12             sb.insert(0, carry%2);
13             carry /= 2;
14             
15             i--;
16             j--;
17         }
18         
19         return sb.toString();
20     }
21 }

类似Plus OneAdd Strings.

posted @ 2015-08-15 09:36  Dylan_Java_NYC  阅读(220)  评论(0编辑  收藏  举报