码迷,mamicode.com
首页 > 其他好文 > 详细

67. Add Binary

时间:2018-07-17 00:48:45      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:dbi   ||   problems   nta   tps   har   bsp   size   discus   

问题描述:

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;
    }
};

 

67. Add Binary

标签:dbi   ||   problems   nta   tps   har   bsp   size   discus   

原文地址:https://www.cnblogs.com/yaoyudadudu/p/9321170.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!