[Show some love to C# :( ]Easy to read C# solution.


  • 0
    M
    public class Solution {
    public string AddBinary(string a, string b) {
    
    if(a==null||b==null)//if null return
    	{
    		return "";
    }
    
    int maxLength = Math.Max(a.Length,b.Length); //prepare result array
    char[] result = new char[maxLength+1];
    for(int j = 0;j<result.Length;j++)
        result[j]='0';
    
    int carry = 0;
    for(int i = 0;i<result.Length;i++) // I just mimicked human addition
    {
    int sum = 0;
    
    	if(a.Length-i-1>=0)
    		sum+=(a[a.Length-i-1]-'0');
    	if(b.Length-i-1>=0)
    		sum+=(b[b.Length-i-1]-'0');
    	sum+=carry;
    
    	result[result.Length-i-1] = (char)(sum%2+'0');
    	carry = sum/2;
    }
    
    if(result[0]=='0') // return result if carry not overflowed
    	return new String(result).Substring(1);
    	else
    		return new String(result);
    
    }
    }
    

    I just mimicked human addition with for loops. I had trouble with char default values in my array so that's why I just fill it with zeros.

    Any comment or question appreciated.


Log in to reply
 

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