Elegant Java Solution Without Math Calculations

  • 0
    public class Solution {
        public String addBinary(String a, String b) {
            if(a==null || b==null) return "";
            boolean add = false;
            StringBuilder sum = new StringBuilder("");
            for(int i =0; i < Math.max(a.length(), b.length()); i++){
                boolean value1 = false, value2 = false;
                if(i<a.length()) value1 = (Character.getNumericValue(a.charAt(a.length()-i-1))==0? false: true);
                if(i<b.length()) value2= (Character.getNumericValue(b.charAt(b.length()-i-1))==0? false: true);
                boolean digit = value1^value2^add;
                add = (value1&&value2)||(value1&&add)||(add&&value2);
                sum = sum.insert(0,digit?'1':'0');
            return sum.toString();

Log in to reply

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