two pointer java solution


  • 0
    I
    public String addBinary(String a, String b) {
    		if (b == null || b.length() == 0)
    			return a;
    		if (a == null || a.length() == 0)
    			return b;
    		String s = "";
    		char[] c1 = a.toCharArray();
    		char[] c2 = b.toCharArray();
    		int d = 0;
    		int i = c1.length - 1, j = c2.length - 1;
    		while (i >= 0 && j >= 0) {
    			int res = Character.getNumericValue(c1[i--])
    					+ Character.getNumericValue(c2[j--]) + d;
    			if (res == 2) {
    				res = 0;
    				d = 1;
    			} else if (res == 3) {
    				res = 1;
    				d = 1;
    			} else
    				d = 0;
    			s = res + s;
    		}
    		if (i < 0) {
    			while (j >= 0) {
    				int res = 0 + Character.getNumericValue(c2[j--]) + d;
    				if (res == 2) {
    					res = 0;
    					d = 1;
    				} else
    					d = 0;
    				s = res + s;
    			}
    		} else if (j < 0) {
    			while (i >= 0) {
    				int res = 0 + Character.getNumericValue(c1[i--]) + d;
    				if (res == 2) {
    					res = 0;
    					d = 1;
    				} else
    					d = 0;
    				s = res + s;
    			}
    		}
    		return d == 1 ? d + s : s;
    	}

Log in to reply
 

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