General Java solution in 5 ms


  • 0
    G

    public class Solution {
    public String addBinary(String a, String b) {
    if(a.equals("0")) return b;
    if(b.equals("0")) return a;
    String result="";
    int alen = a.length(),blen = b.length(),temp=0;
    while(alen>0 || blen>0 || temp>0){
    int aval=0,bval=0;
    if(alen>0){
    aval = a.charAt(alen-1)=='0'?0:1;
    alen--;
    }
    if(blen>0){
    bval = b.charAt(blen-1)=='0'?0:1;
    blen--;
    }
    temp += aval;
    temp += bval;
    result = (temp%2==0?'0':'1')+result;
    temp = temp>>1;
    }
    return result;
    }
    }


Log in to reply
 

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