LeetCode | 67. Add Binary

Description

Given two binary strings, return their sum (also a binary string).
For example, a = "11", b = "1", Return "100".

Solution

Thought

  • Read each char of both strings from right to left ;
  • Add these two chars and the last carry output if exists, then calculate the carry output and append the result string;

sum = num_a+num_b+carry;
carry = sum/2;         //decimal system : carry = sum/10
result. append(sum%2);     //decimal system : append(sum%10)

Attention

  • Use StringBulider to instead of String.

The system creates a new string when we use "+" to add strings every time which is a waste of time ;
Run time:StringBulider < StringBuffer < String

  • Use ?A : B to instead of If ;
  • When finished, remember to reverse the result ;
  • When type char are converted into type int, it will be equal to the value of the corresponding ASCII code. So we don't do this way.

char a = '0';
int a1 = Integer.valueOf(a);    //a1=48

Method of StringBuilder

  • append(String str/Char c);
  • insert(int offset, String str/Char c);
  • delete(int startIndex, int endIndex);
  • replace(char a, char b);
  • toString();
  • reverse();

Code

class Solution {
    public String addBinary(String a, String b) {
        int len_a = a.length();
        int len_b = b.length();
        int advance = 0;
        StringBuilder result = new StringBuilder();
        if(len_a==0&&len_b==0){
            result.append('0');
            return result.toString();
        }
        while(len_a>0 || len_b>0 || advance==1 ){
            int num_a = len_a>0?a.charAt(len_a-1)-'0':0;
            int num_b = len_b>0?b.charAt(len_b-1)-'0':0;
            int num_sum = num_a+num_b+advance;
            result.append(String.valueOf(num_sum%2));
            advance=num_sum/2;
            len_a--;
            len_b--;
        }
    return result.reverse().toString();  
    }
}
Comments
Write a Comment