博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Add Binary leetcode
阅读量:6828 次
发布时间:2019-06-26

本文共 729 字,大约阅读时间需要 2 分钟。

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

For example,

a = "11"
b = "1"
Return "100".

 

 to see which companies asked this question

 
二进制string加法,可优化代码,不过算法已经接近最优
string addBinary(string a, string b) {    string ret;    int lenA = a.size() - 1;    int lenB = b.size() - 1;    int cur;    int add = 0;    while (lenA >= 0 || lenB >= 0)    {        int numA = lenA >= 0 ? a[lenA] - '0' : 0;        int numB = lenB >= 0 ? b[lenB] - '0' : 0;        int num = numA + numB + add;        cur = num & 1;        add = num >> 1;        ret.insert(0, 1, char('0' + cur));        lenA--;        lenB--;    }    if (add == 1)        ret.insert(0, 1, '1');    return ret;}

 

转载于:https://www.cnblogs.com/sdlwlxf/p/5111039.html

你可能感兴趣的文章