Simple JavaSolution


  • 0
    S

    Approach:

    1. Iterate through the length of maximum of two strings.
    2. At any point we will have three digits to add, operand1, operand2, carry.
    3. Obtain the sum to find carry and inPlace value and insert it into new string at beginning.
    4. Repeat the above process.
    5. Add any carry propagated to beginning before returning the result.

    Code:

    public String addBinary(String a, String b) {
            int ia = a.length()-1, ib = b.length()-1;
            StringBuilder sb = new StringBuilder();
            int carry = 0;
            while(ia >= 0 || ib >= 0){
                int o1 = (ia >= 0)? ((a.charAt(ia) == '1')? 1: 0): 0;
                int o2 = (ib >= 0)? ((b.charAt(ib) == '1')? 1: 0): 0;
                int sum = o1 + o2 + carry;
                carry = sum / 2;
                int rem = sum % 2;
                sb.insert(0, rem+"");
                ia--; ib--;
            }
            if(carry != 0)
                sb.insert(0, ""+carry);
            return sb.toString();
        }
    

Log in to reply
 

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