Tuesday, February 26, 2013

[LeetCode] Add Binary

Thought:
It is easy.

Code:
public class Solution {
    public String addBinary(String a, String b) {
        StringBuilder result = new StringBuilder();
        int m = a.length();
        int n = b.length();
        int len = Math.max(m, n);
        int carry = 0;
       
        for(int i = 0; i < len; i++) {
            int x = getIndex(a, m - 1 - i);
            int y = getIndex(b, n - 1 - i);
            result.insert(0, (x + y + carry) % 2);
            carry = (x + y + carry) / 2;
        }
        if(carry == 1) {
            result.insert(0, 1);
        }
        return result.toString();       
    }
    public int getIndex(String s, int index) {
        if(index < 0 || index > s.length() - 1) {
            return 0;
        }else {
            return s.charAt(index) == '0'? 0: 1;
        }
    }
}


Second Round Code:

public class Solution {
    public String addBinary(String a, String b) {
        StringBuilder ret = new StringBuilder();        
        int carry = 0;
        int retLength = Math.max(a.length(), b.length());
        int i = a.length() - 1;
        int j = b.length() - 1;

        while (retLength-- > 0) {
            int temp = getInt(a, i--) + getInt(b, j--) + carry;
            ret.append(temp % 2);
            carry = temp / 2;            
        }
        if (carry == 1) ret.append(1);
        return ret.reverse().toString();
    }
    public int getInt (String s, int index) {
        if (index < 0 || index > s.length() - 1) return 0;
        return s.charAt(index) == '0'? 0 : 1 ;
    }
}

No comments:

Post a Comment