Damn simple java code, plus comment.


  • 0
    Z
    /**
     * 1.Dont have to reverse string- use small functions to wrap reverse index accessing.
     * 2.Alloc 1 more space, and return substring from idx 1 if needed.
     */
    public class Solution {
        public String addBinary(String a, String b) {
            // if 1 more byte is not needed, just return substring starting from idx 1.
            char[] cs = new char[1 + Math.max(a.length(), b.length())];
            int carry = 0;
            
            for(int i =0; i < cs.length; i ++){
                int val = getReverse(a, i) + getReverse(b, i) + carry;
                carry = val /2;
                val %= 2;
                setReverse(cs, i, val);
            }
            
            String s = new String(cs);
            return s.charAt(0) == '0' ? s.substring(1): s;
        }
        
        // 
        int getReverse(String s, int i){
            int idx = s.length() -1 - i;
            return idx < 0 ? 0 : s.charAt(idx) - '0';
        }
        
        void setReverse(char[] cs, int i, int val){
            cs[cs.length -1 - i] = (char)('0' + val);
        }
    }
    

Log in to reply
 

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