Java accepted solution: want to cut down on lines if possible


  • 0
    G
    public class Solution {
        public String addBinary(String a, String b) {
            StringBuilder sb = new StringBuilder();
            int i = a.length()-1, j = b.length() -1,m=0,n=0, carry=0;
            while(i>=0 && j>=0)
            {
                m = Character.getNumericValue(a.charAt(i--));
                n = Character.getNumericValue(b.charAt(j--));
                sb.insert(0,(carry^m^n));
                if(m+n+carry>1)
                    carry=1;
                else
                    carry=0;
            }
            while(i>=0)
            {
                m = Character.getNumericValue(a.charAt(i--));
                sb.insert(0,carry ^ m);
                carry &= m;
            }
            while(j>=0)
            {
                m = Character.getNumericValue(b.charAt(j--));
                sb.insert(0,carry ^ m);
                carry &= m;
            }
            if(carry==1)
                sb.insert(0,1);
            return sb.toString();
        }
    }

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example


Log in to reply
 

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