67. Add Binary

Posted zle1992

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了67. Add Binary相关的知识,希望对你有一定的参考价值。



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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode67. Add Binary

67. Add Binary

LeetCode----67. Add Binary(java)

67. Add Binary

67. Add Binary

leetcode67. Add Binary