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

67. Add Binary

时间:2019-01-06 13:32:20      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:str   ||   NPU   ase   lin   class   base   pre   string   



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

 

67. Add Binary

标签:str   ||   NPU   ase   lin   class   base   pre   string   

原文地址:https://www.cnblogs.com/zle1992/p/10228290.html

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