Java - 2ms beat 98%


  • 0
    N
    public class Solution {
        public String addBinary(String a, String b) {
            if (a == null) return b;
            if (b == null) return a;
            
            return a.length() > b.length() ? add(a, b) : add(b, a);
        }
        
        private String add(String l, String s){
            char[] lc = l.toCharArray();
            char[] sc = s.toCharArray();
            
            int offset = lc.length - sc.length;
            char e = '0';        
            
            for (int i = sc.length-1; i >=0; i--) {
                int li = i+offset;
                switch (lc[li] + sc[i] + e - 144) {
                    case 0: lc[li] = '0'; break;
                    case 1: lc[li] = '1'; e = '0'; break;
                    case 2: lc[li] = '0'; e = '1'; break;
                    case 3: lc[li] = '1'; break;
                }
            }
            
            if (e == '0') return new String(lc);
            
            for (int i = offset - 1; i >=0; i--) {
                switch (lc[i] + e - 96) {
                    case 0: return new String(lc);
                    case 1: lc[i] = '1'; return new String(lc);
                    case 2: lc[i] = '0'; e = '1';
                }
            }
            return e == '1' ? "1" + new String(lc) : new String(lc);
        }
    }
    

Log in to reply
 

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