My Accepted Java solution(226ms)


  • 0
    O
    public class Solution {
        public String addBinary(String a, String b) {
            if (a.length() == 0) {
    			return b;
    		}
    		if (b.length() == 0) {
    			return a;
    		}
    		
    		StringBuilder result = new StringBuilder();
    		int size = a.length() < b.length() ? a.length() : b.length();
    		int i = 0, x = 0;
    		for(i = 0; i < size; i++) {
    			x = (int)(a.charAt(a.length() - i - 1) + b.charAt(b.length() - i - 1) - 96) + x;
    			result.insert(0, x % 2);
    			x = (x - x % 2)/2;
    		}
    		
    		while (i < a.length()) {
    			x = (int)(a.charAt(a.length() - i - 1) - 48) + x;
    			result.insert(0, x % 2);
    			x = (x - x % 2)/2;
    			i++;
    		}
    		
    
    		while (i < b.length()) {
    			x = (int)(b.charAt(b.length() - i - 1) - 48) + x;
    			result.insert(0, x % 2);
    			x = (x - x % 2)/2;
    			i++;
    		}
    		
    		if (x != 0) {
    		    result.insert(0, x);
    		}
    		
    		return result.toString();
        }
    }

Log in to reply
 

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