leetcode 067 Add Binary

来源:互联网 发布:最近mmd喵萝脸型数据 编辑:程序博客网 时间:2024/06/06 01:26

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

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

Subscribe to see which companies asked this question

class Solution {public:    string addBinary(string a, string b) {        int aLen = a.length(), bLen = b.length(), i=0, index=0;if(aLen == 0) return b;if(bLen == 0) return a;if(aLen < bLen) return addBinary(b, a);int cnt=0;for(i = bLen-1, index=aLen-1; i >= 0; i--, index--) {int temp = a[index]-'0'+b[i]-'0'+cnt;cnt = temp/2;temp = temp%2;a[index] = '0'+temp;}for(; index >= 0; index--) {int temp = a[index]-'0'+cnt;cnt = temp/2;temp = temp%2;a[index] = '0'+temp;}if(cnt > 0) {a = '1'+a;}return a;    }};


0 0
原创粉丝点击