My Java solution


  • 0
    K
    public class Solution {
    public String addBinary(String a, String b) {
        
        int carry = 0;
        StringBuilder sb = new StringBuilder();
        
        for (int i = a.length() - 1, j = b.length() - 1; (carry + i) >= 0 || (j + carry) >= 0; i--, j--) {
            int result = getBit(a, i) + getBit(b, j) + carry;
            switch (result) {
                case 0:
                    carry = 0;
                    sb.insert(0, 0);
                    break;
                case 1:
                    carry = 0;
                    sb.insert(0, 1);
                    break;
                case 2:
                    carry = 1;
                    sb.insert(0, 0);
                    break;
                case 3:
                    carry = 1;
                    sb.insert(0, 1);
                    break;
            }
            
        }
         return sb.toString();
    }
    
    private int getBit(String str, int index) {
        if (index < 0 || index >= str.length()) {
            return 0;
        }
        return str.charAt(index) - 48;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.