Solution for binary number addition


  • 0
    M

    class Solution {
    public String addBinary(String bin1, String bin2) {
    {

        int i = bin1.length()-1;
        int j = bin2.length()-1;
        String carry = null;
        String sum = null;
        String result = "" ;
        while(i >=0 && j >=0 ){
           if(bin1.charAt(i) == '1' && bin2.charAt(j) == '1'){
               if(carry == "1"){
                   sum = "1";
                   carry= "1";
               }
               else{
                   sum ="0";
                   carry = "1";
               }
           }else if(bin1.charAt(i) == '0' && bin2.charAt(j) == '0'){
               if(carry == "1"){
                   sum = "1";
                   carry= "0";
               }
               else{
                   sum ="0";
                   carry = "0";
               }
           } else{
               if(carry == "1"){
                   sum = "0";
                   carry= "1";
               }
               else{
                   sum ="1";
                   carry = "0";
               }
           }
    
           result = sum + result;
            i--;
            j--;
        }
    
        while(i >= 0){
            if(bin1.charAt(i) == '1'){
                if(carry == "1"){
                    sum = "0";
                    carry= "1";
                }
                else{
                    sum ="1";
                    carry = "0";
                }
            }else{
                if(carry == "1"){
                    sum = "1";
                    carry= "0";
                }
                else{
                    sum ="0";
                    carry = "0";
                }
            }
            result = sum + result;
            i--;
        }
    
        while(j >=0){
            if(bin2.charAt(j) == '1'){
                if(carry == "1"){
                    sum = "0";
                    carry= "1";
                }
                else{
                    sum ="1";
                    carry = "0";
                }
            }else{
                if(carry == "1"){
                    sum = "1";
                    carry= "0";
                }
                else{
                    sum ="0";
                    carry = "0";
                }
            }
            result = sum + result;
            j--;
        }
        if(carry == "0"){
            return result;
        }
        result = carry + result;
    
    
        return result;
    }
    }
    

    }


Log in to reply
 

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