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

67. Add Binary

发布时间:2020-12-14 05:16:39 所属栏目:大数据 来源:网络整理
导读: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:


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"



 1 class Solution {
 2 public:
 3     string addBinary(string a,string b) {
 4         string res;
 5         int carry = 0;
 6         int a_end = a.size()-1;
 7         int b_end = b.size()-1;
 8         while(a_end>=0||b_end>=0){
 9             int i = (a_end>=0 &&a[a_end]==1);
10             int j = (b_end>=0 &&b[b_end]==1);
11             int temp = i+j+carry;
12             if(temp>=2){
13                 res=to_string(temp-2)+res;
14                 carry =1;
15             }
16             else{
17                 res=to_string(temp)+res;
18                 carry =0;    
19             }
20             a_end--;
21             b_end--;
22            
23         }
24         if(carry)
25             res=1+res;
26         return res;
27     }
28 };

(编辑:李大同)

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

    推荐文章
      热点阅读