加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

67. Add Binary

发布时间:2020-12-14 03:20:58 所属栏目:大数据 来源:网络整理
导读:问题描述: Given two binary strings,return their sum (also a binary string). The input strings are both?non-empty?and contains only characters? 1 ?or? 0 . Example 1: Input: a = "11",b = "1"Output: "100" Example 2: Input: a = "1010",b = "10

问题描述:

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

The input strings are both?non-empty?and contains only characters?1?or?0.

Example 1:

Input: a = "11",b = "1"
Output: "100"

Example 2:

Input: a = "1010",b = "1011"
Output: "10101"

?

解题思路:

我原来的代码巨长无比(就是正常的思路)

想看看有没有人又简短的代码。

我就知道,一定有。

参考:Short code by c++

?

代码:

class Solution {
public:
    string addBinary(string a,string b) {
        int len1 = a.size();
        if(len1 == 0) return b;
        int len2 = b.size();
        if(len2 == 0) return a;
        
        int c = 0,i = len1-1,j = len2-1;
        string s;
        while(c > 0 || i > -1 || j > -1){
            c += i > -1 ? a[i--] - 0 : 0;
            c += j > -1 ? b[j--] - 0 : 0;
            s.push_back(char(c%2 + 0));
            c =  c/2;
        }
        reverse(s.begin(),s.end());
        return s;
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读