首页 > 代码库 > Add Binary

Add Binary

Given two binary strings, return their sum (also a binary string).

For example,

a = "11"

b = "1"

Return "100".

思路:

 1 class Solution { 2 public: 3     string addBinary( string a, string b ) { 4         int alen = a.length(), blen = b.length(); 5         string result( max( alen, blen ), 0 ); 6         int carry = 0, i = max( alen, blen ); 7         while( --i >= 0 ) { 8             if( alen > 0 ) { --alen; carry += a[alen]-0; } 9             if( blen > 0 ) { --blen; carry += b[blen]-0; }10             result[i] += carry % 2;11             carry /= 2;12         }13         if( carry ) { result.insert( 0, "1" ); }14         return result;15     }16 };

 

Add Binary