Saturday, November 28, 2015

[leetcode]Add Binary

Potential improvement, 用1个loop, out of bound 用expression赋值0, 还有不需要用Integer value of 直接减一减就好了
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class Solution {
    public String addBinary(String a, String b) {
        if (a == null || a.equals("")) return b;
        if (b == null || b.equals("")) return a;
        int i = a.length()-1;
        int j = b.length()-1;
        int carry = 0;
        String result = "";
        while (i >= 0 && j >= 0){
            int v1 = Integer.valueOf(a.charAt(i--)+"");
            int v2 = Integer.valueOf(b.charAt(j--)+"");
            int sum = (v1+v2+carry)%2;
            carry = (v1+v2+carry)/2;
            result = sum+result;
        }
        
        while (i>=0){
            int v1 = Integer.valueOf(a.charAt(i--)+"");
            int sum = (v1+carry)%2;
            carry = (v1+carry)/2;
            result = sum+result;
        }
        
        while (j>=0){
            int v2 = Integer.valueOf(b.charAt(j--)+"");
            int sum = (v2+carry)%2;
            carry = (v2+carry)/2;
            result = sum+result;
        }
        if (carry == 1){
            result = "1"+result;
        }
        
        return result;
    }
}

No comments:

Post a Comment