首页 > 代码库 > Leetcode 数 Add Binary

Leetcode 数 Add Binary

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


Add Binary

 Total Accepted: 9509 Total Submissions: 37699

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

For example,
a = "11"
b = "1"
Return "100".


题意:给定两个二进制字符串,返回它们的和

思路:

1.按最长的循环,短的前面补零
2.因为变量少,不用考虑节省空间,定义为int最行了
3.用二进制可能会快一点。不过实现会麻烦一些

复杂度:时间O(m+n),空间O(m+n)


class Solution {
public:
     string addBinary(string a, string b){
    	string result;
    	int carry = 0;
    	int scale = 2;
    	for(int i = a.size() - 1, j = b.size() - 1; i >= 0 || j >= 0; i--,j--){
    		int ai = i > -1 ? a[i] - ‘0‘ : 0;
    		int bi = j > -1 ? b[j] - ‘0‘ : 0;
    		int residual = (ai + bi + carry) % scale;
    		carry = (ai + bi + carry) / scale;
    		result.insert(result.begin(), residual + ‘0‘);
    	} 
    	if(carry) result.insert(result.begin(), carry + ‘0‘);
    	return result;
    }
};