2ms beat 98.55% Java Solution


  • 0
    I

    Use ascaii code to calculate each bit

    	public String solution(String a, String b) {
    		
    		int len_a = a.length();
    		int len_b = b.length();
    
    		int len_s;
    		char[] sum = new char[len_a > len_b ? len_a + 1 : len_b + 1];
                    // Set all the elements in sum array to character '0', therefore it would be '1' if you add int 1 to it 
    		for (int i = 0; i < sum.length; i++)
    			sum[i] = '0';
    		len_s = sum.length - 1;
    
    		int i = len_a - 1, j = len_b - 1;
    		while (i > -1 || j > -1) {
    			sum[len_s] += binaryBitAdd(i > -1 ? a.charAt(i) : '0', j > -1 ? b.charAt(j) : '0');
    			if (sum[len_s] > '1') {
    				sum[len_s - 1]++;
    				sum[len_s] -= 2;
    			}
    			i--;
    			j--;
    			len_s--;
    		}
                    // If the start of the char array is 0 then return the rest otherwise return the whole array
    		return new String(sum, sum[0] == '1' ? 0 : 1, sum[0] == '1' ? sum.length : sum.length - 1); 
    
    
    	}
    
    	public int binaryBitAdd(char a, char b) {
    		if (a == '1' && b == '1')
    			return 2;
    		if (a == '0' && b == '0')
    			return 0;
    		return 1;
    	}
    

  • 0
    I
    This post is deleted!

Log in to reply
 

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