标签:style blog color io for ar div log amp
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 };
标签:style blog color io for ar div log amp
原文地址:http://www.cnblogs.com/moderate-fish/p/3935216.html