My Simple Accepted Java Solution


  • 1
    A
    public class Solution {
        public String addBinary(String a, String b) {
            String res = "";
            int carryOver = 0;
            for(int i = a.length()-1, j = b.length()-1; i>=0 || j>=0; i--, j--){
                int ai = ((i<0)?0:Integer.parseInt(a.charAt(i)+""));
                int bi = ((j<0)?0:Integer.parseInt(b.charAt(j)+""));
                res = ((ai ^ bi)^carryOver) + res;
                carryOver = ((ai+bi+carryOver)>1)?1:0;
            }
            if(carryOver==1)
                res = 1+res;
            return res;
        }
    }

  • 0
    R

    Neat solution. One comment, you are using string concatenation which is expensive. I am curious to know how the performance of your program would change if you use a StringBuffer instead..


  • 0
    O

    ai, bi variables must be initialized outside the for it is also expensive.


Log in to reply
 

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