Java accepted solution for Add Binary for reference


  • 0
    B
    public class Solution {
        public String addBinary(String a, String b) {
            String[] src = alignString(a, b);
    
    		src[0] = new StringBuilder(src[0]).reverse().toString();
    		src[1] = new StringBuilder(src[1]).reverse().toString();
    
    		StringBuilder sb = new StringBuilder();
    		char carry = '0';
    		char[] tmpResult = new char[] { '0', '0' };
    
    		for (int i = 0; i < src[0].length(); i++) {
    			tmpResult = charBinarySum(src[0].charAt(i), src[1].charAt(i), tmpResult[1]);
    
    			sb.append(tmpResult[0]);
    		}
    
    		if (tmpResult[1] == '1') {
    			sb.append('1');
    		}
    
    		return sb.reverse().toString();
        }
        
        public String[] alignString(String a, String b)
    	{
    		String newA = a;
    		String newB = b;
    
    		if (a.length() > b.length()) {
    			newB = new StringBuilder(repeatString("0", a.length() - b.length())).append(b).toString();
    		}
    		if (b.length() > a.length()) {
    			newA = new StringBuilder(repeatString("0", b.length() - a.length())).append(a).toString();
    		}
    
    		return new String[] { newA, newB };
    	}
    
    	private String repeatString(String s, int times)
    	{
    		StringBuffer b = new StringBuffer();
    
    		for (int i = 0; i < times; i++) {
    			b.append(s);
    		}
    
    		return  b.toString();
    	}
    
    	public char[] charBinarySum(char a, char b, char c)
    	{
    		char[] result = new char[2];
    
    		int sum =
    			Integer.parseInt(String.valueOf(a)) +
    			Integer.parseInt(String.valueOf(b)) +
    			Integer.parseInt(String.valueOf(c));
    
    		if (sum == 0) {
    			result[0] = '0';
    			result[1] = '0';
    		}
    		if (sum == 1) {
    			result[0] = '1';
    			result[1] = '0';
    		}
    		if (sum == 2) {
    			result[0] = '0';
    			result[1] = '1';
    		}
    		if (sum == 3) {
    			result[0] = '1';
    			result[1] = '1';
    		}
    
    		return result;
    	}
    }

Log in to reply
 

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