3ms code beats 80.92%, without any calculation


  • 0
    K

    Unlike other methods that sum up the character values and % method to get the carry over, I just keep a reference of prev character (carry over) and append it appropriate under different condition.

    1. if current char is '0' and '0' || '1' and '1', we will append the prev character (carry over), then we just set carry over to be either 0 or 1 respectively.
    2. if the characters are different, '0' and '1', if carry over = 1, we append '0' else we append '1'. Now, the carry over stay the same, we save the work of calculating or assigning the value.
    	public String addBinary(String a, String b) {
    		int m = a.length() - 1, n = b.length() - 1;
    		StringBuilder sb = new StringBuilder();
    		char prev = '0';
    		while (m >= 0 || n >= 0) {
    			char c1 = m < 0 ? '0' : a.charAt(m);
    			char c2 = n < 0 ? '0' : b.charAt(n);
    			if (c1 == c2) {
    				sb.append(prev);
    				prev = c1;
    			} else if (prev == '1') {
    				sb.append('0');
    			} else {
    				sb.append('1');
    			}
    			m--;
    			n--;
    		}
    		if (prev == '1') sb.append('1');
    		return sb.reverse().toString();
    	}
    

Log in to reply
 

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