13 Lines Easy JAVA Solution, Simple and Elegant


  • 14
    W
    public String addBinary(String a, String b) {
        int lena = a.length();
        int lenb = b.length();
        int i =0, carry = 0;
        String res = "";
        while(i<lena || i<lenb || carry!=0){
            int x = (i<lena) ? Character.getNumericValue(a.charAt(lena - 1 - i)) : 0;
            int y = (i<lenb) ? Character.getNumericValue(b.charAt(lenb - 1 - i)) : 0;
            res = (x + y + carry)%2 + res;
            carry = (x + y + carry)/2;
            i++;
        }
        return res;
    }

  • 1
    W

    if you don't want to use getNumericValue:

    public class Solution {
    public String addBinary(String a, String b) {
        int carry=0;
        String result="";
        int i=0;
        int alen=a.length();
        int blen=b.length();
        while(i<alen||i<blen||carry!=0){
            int x=(i<alen)?((a.charAt(alen-1-i)=='1')?1:0):0;
            int y=(i<blen)?((b.charAt(blen-1-i)=='1')?1:0):0;
            result=(x+y+carry)%2+result;
            carry=(x+y+carry)/2;
            i++;
        }
        return result;
    }
    

    }


  • 0
    R

    What is carry used for?


  • 1
    K

    use StringBuilder is much better


Log in to reply
 

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