LeetCode 67. Add Binary

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

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


// Only need to pay attention that adding is from the end of string. 

This problem is similar to the add one problem. http://blog.csdn.net/github_34333284/article/details/51103310

#include <string>
#include <iostream>
using namespace std;

// a = "11", b = "1" --> "100"

string addBinary(string a, string b) {
    if(a.size() == 0) return b;
    if(b.size() == 0) return a;
    int aSize = a.size() - 1;
    int bSize = b.size() - 1;
    string res = "";
    int overflow = 0;
    while(aSize >= 0 && bSize >= 0) {
        int tmp = a[aSize] - '0' + b[bSize] - '0' + overflow;
        overflow = tmp / 2;
        res = to_string(tmp % 2) + res;
        aSize--;
        bSize--;
    }
    while(aSize >= 0) {
        int tmp = a[aSize--] - '0' + overflow;
        overflow = tmp / 2;
        res = to_string(tmp % 2) + res;
    }
    while(bSize >= 0) {
        int tmp = b[bSize--] - '0' + overflow;
        overflow = tmp / 2;
        res = to_string(tmp % 2) + res;
    }
    if(overflow) res = "1" + res;
    return res;
}

int main(void) {
    string a = "11";
    string b = "1";
    string res = addBinary(a, b);
    cout << res << endl;
}

Maybe It is better to make code clean.

#include <string>
#include <iostream>
using namespace std;

string addBinary(string a, string b) {
  if(a.size() == 0) return b;
  if(b.size() == 0) return a;
  int aEnd = a.size() - 1;
  int bEnd = b.size() - 1;
  int overflow = 0;
  string res = "";
  while(aEnd >= 0 || bEnd >= 0) {
    int sum = (aEnd < 0 ? 0 : (a[aEnd] - '0')) + (bEnd < 0 ? 0 : (b[bEnd] - '0')) + overflow;
    overflow = sum / 2;
    sum = sum % 2;
    res = to_string(sum) + res;
    aEnd--;
    bEnd--;
  }
  if(overflow) res = "1" + res;
  return res;
}

int main(void) {
  cout << addBinary("11", "1") << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值