Tuesday, April 2, 2013

Add Binary(C++ code)

LeetCode Add Binary Apr 2 '12
难度2,出现频率4
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".

思路: 从末位开始相加,进位存在res里面,当前数字插入到string首位。

string addBinary(string a, string b){
       int m = a.length() - 1;
       int n = b.length() - 1;
       int res = 0;
       string out;


       while(m >= 0 || n >= 0 || res > 0){
            int add = res;
            if(m >= 0)  add += a[m--] - '0';
            if(n >= 0)  add += b[n--] - '0';
            res = (add>1)?1 : 0;
            out = string(1, ('0'+ (add&1))) + out;
                    
       }
      
       return out;  
      
}

No comments:

Post a Comment