Simple Java solution


  • 0
    T
    public class Solution {
        
        public String addBinary(String a, String b) {
            
            if(a == null || b == null){
                return null;
            }
            
            int currentCarry = 0;
            String str = "";
            
            int aIndex = a.length()-1;
            int bIndex = b.length()-1;
            
            while(aIndex >= 0 || bIndex >= 0){
                int a_int = 0;
                int b_int = 0;
                
                if(aIndex >= 0){
                    a_int = Character.getNumericValue(a.charAt(aIndex--));
                }
                
                if(bIndex >= 0){
                    b_int = Character.getNumericValue(b.charAt(bIndex--));
                }
                
                int sum = a_int + b_int + currentCarry;
                str = (sum % 2) + str;
                currentCarry = sum < 2 ? 0: 1;
                
            }
            
            if(currentCarry == 1){
                str = 1 + str;
            }
            
            return str;
        }
    }
    

Log in to reply
 

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