Easy accepted java solution O(n)


  • 0
    K
     public String addBinary(String a, String b) {
        
        char[] array1 = a.toCharArray();
        char[] array2 = b.toCharArray();
    
        int m = array1.length-1;
        int n = array2.length-1;
        
        String result = "";
        int carry = 0;
        int value = 0;
        while( m >=0 || n >=0) {
            
            char a1 = '0';
            char a2 = '0';
            
            if( m >= 0) {
                a1 = array1[m--];
            }
            if(n >= 0) {
                a2 = array2[n--];
            }
            
            value = (a1 - '0') + (a2 - '0') + carry;
            
            if( value  == 0) { // all zeros
                result = "0" + result;
                //carry is already 0
            } else if (value == 1) { // just 1
                result = "1" + result;
                carry = 0;
            } else if (value == 2) { // 2 1s 
                result = "0" + result;
                carry = 1;
            } else if (value == 3) { //3 1s
                result = "1" + result;
                // we already know carry is 1
            }
        }
        
        if(carry == 1) {
            result = carry + result;
        }
        
        return result;
    }

  • 0
    H

    This is better

    public class Solution {
        public String addBinary(String a, String b) {
            char[] m=a.toCharArray();
            char[] n=b.toCharArray();
            
            int l1=m.length-1;
            int l2=n.length-1;
            int carry=0;
            int tmp1,tmp2;
            String res="";
            while ( l1>=0 || l2>=0){
                tmp1=0;
                tmp2=0;
               if (l1>=0) tmp1=m[l1--]-'0';
               if (l2>=0) tmp2=n[l2--]-'0';
               int tmp=tmp1+tmp2+carry;
               res=tmp%2+res;
               carry=tmp/2;
            }
            if (carry==1)
            res='1'+res;
            return res;
        }
    }

Log in to reply
 

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