runtime 0 ms, beats 100% of cpp submissions
O(m+n) solution with explanation

tags: string

Add Binary

šŸ“– description

ēµ¦å®šå…©å€‹ 01 陣列 a态b ļ¼Œč«‹ę±‚å°‡å…©č€…ē›øåŠ ä¹˜ę–°ēš„å­—äø²å›žå‚³ć€‚

ex.
    Input: 
        a = "1010", b = "1011"

    Output: "10101"

šŸ§  solution

ę ¹ę“šé”Œę„ęØ”ę“¬äø€ę¬”č؈ē®—ļ¼ŒåŖéœ€č¦ę³Øę„é”å¤–č™•ē†é€²ä½å…¶ę³å³åÆ怂

ā³ time complexity

éę­·å…©å€‹å­—äø²ļ¼Œę™‚é–“č¤‡é›œåŗ¦ O(m+n) ļ¼Œå…¶äø­ m, n 代č”Ø兩個字äø²ēš„é•·åŗ¦ć€‚
ēø½ę™‚é–“č¤‡é›œåŗ¦ O(m+n)

šŸ“ code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(),a.end()); // éæ免長åŗ¦äøåŒ
reverse(b.begin(),b.end());
int n = max(a.size(),b.size());
string ans = "";
int carry = 0;
int cnt = 0;
for(int i=0;i<n;i++){
int tmp = carry;
if(i<a.size()){
tmp+=a[i]-'0';
}
if(i<b.size()){
tmp+=b[i]-'0';
}
if(tmp>=2){
carry = 1;
tmp-=2;
}
else{
carry = 0;
}
ans+=tmp+'0';
}
if(carry == 1){ // 處ē†ęœ€é«˜ä½é€²ä½
ans+='1';
}
reverse(ans.begin(),ans.end()); // č½‰å›žä¾†
return ans;
}
};