[leetcode] Add Binary
时间:2014-04-28 02:05:20
收藏:0
阅读:502
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b
= "1"
Return "100"
.
给定两个二进制的字符串,返回他们的和。
对于a,b两个二进制字符串,首先通过交换使a的长度小于b的长度。然后在a前面补0令ab的长度相同。然后从最后一位开始往前逐步使用加法规则相加,需要注意的是carry表示前一位向这一位的进位,如果在第k位时,a[i]+b[i]+carry <= 1,则需要把carry清零。
最后判断carry是否为零,若不为零则在前面添加一个carry。
代码如下:
1 class Solution { 2 public: 3 string addBinary(string a, string b) { 4 5 6 if( a.length() > b.length() ) 7 { 8 string tmp = a; 9 a = b; 10 b = tmp; 11 } 12 13 string zero = "0"; 14 15 while( a.length() != b.length() ) 16 { 17 a = zero + a; 18 } 19 20 21 int len = b.length(); 22 int carry = 0; 23 24 string res = ""; 25 for( int i = 1 ; i <= len ; i++ ) 26 { 27 int cur = 0; 28 cur = a[len-i] - ‘0‘ + b[len-i] - ‘0‘ + carry; 29 if( cur > 1 ) 30 { 31 cur -= 2; 32 carry = 1; 33 } 34 else 35 { 36 carry = 0; 37 } 38 char tmp = cur + ‘0‘; 39 res = tmp + res; 40 } 41 42 if( carry != 0 ) 43 { 44 char tmp = carry + ‘0‘; 45 res = tmp + res; 46 } 47 48 return res; 49 } 50 };
评论(0)