binary ํ์์ ๋ฌธ์์ด ๋๊ฐ๊ฐ ์ฃผ์ด์ง๊ณ ๋ ๊ฐ์ binary ๋ก ๋ ํ์ ๋ ๋์ค๋ binary ํํ์ ๋ฌธ์์ด์ ๋ฆฌํดํ๋ ๋ฌธ์ ๋ค.
๊ฐ ๋ฌธ์์ด์ ๋ค์์ ๋ถํฐ ๊ฐ์ ๋ํ๋ฉด์ 1,1 ์ผ ๊ฒฝ์ฐ carry (์ฝ๋์์ r) ๋ฅผ 1๋ก ๋ฐ๊ฟ์ฃผ์๋ค. ๊ทธ๋ฆฌ๊ณ ๊ฐ ๊ฐ์ ๋ฐ๋ผ ๋ฐฐ์ด์ ๋ฃ์ด์ฃผ์๋ค. ๊ฒฐ๊ณผ ๊ฐ์ ๊ฑฐ๊พธ๋ก ์ธ๋ฑ์ค๋ฅผ ๊ฐ์ ์ํค๋ฉด์ ๋ํ๊ธฐ ๋๋ฌธ์ ๋ฆฌ์คํธ๋ฅผ ๋ค์ง์ด์ ๋ฆฌํดํ๋ค.
ํํ ํ๋ ๋ง์ ๊ณต์์ ๋ฌธ์์ด๋ก ํ์ดํ ๊ฒ์ด๋ค.
class Solution:
def addBinary(self, a: 'str', b: 'str') -> 'str':
if len(a) == 0 and len(b) != 0:
return b
if len(b) == 0 and len(a) != 0:
return a
i, j = len(a) - 1, len(b) - 1
r = "0"
result = []
while i >= 0 and j >= 0:
p, q = a[i], b[j]
if r == "1":
if p == "1" and q == "1":
result.append("1")
elif (p == "1" and q == "0") or (p == "0" and q == "1"):
result.append("0")
else:
result.append("1")
r = "0"
else:
if p == "1" and q == "1":
result.append("0")
r = "1"
elif p == "0" and q == "0":
result.append("0")
else:
result.append("1")
i -= 1
j -= 1
if len(a) > len(b):
while i >= 0:
if r == "1":
if a[i] == "1":
result.append("0")
r = "1"
else:
result.append("1")
r = "0"
else:
result.append(a[i])
i -= 1
elif len(b) > len(a):
while j >= 0:
if r == "1":
if b[j] == "1":
result.append("0")
r = "1"
else:
result.append("1")
r = "0"
else:
result.append(b[j])
j -= 1
if r == "1":
result.append(r)
return "".join(result[::-1])
์ฝ๋๋ฅผ ๋ ๊น๋ํ๊ฒ ํ ์๋ ์์ ๊ฒ ๊ฐ์๋ฐ, ๊ทธ๊ฒ์ ์ค์ํ์ง ์์ผ๋ ํจ์ค.
์๊ฐ ๋ณต์ก๋๋ ๋ฌธ์์ด ๊ธธ์ด๊ฐ ํฐ ์ชฝ์ ์ํฅ์ ๋ฐ๋๋ค. ๋ง์ฝ ๊ฐ๊ฐ N, M ๊ธธ์ด์ ๋ฌธ์์ด์ด๊ณ N < M ์ด๋ฉด O(M) ์ด ๋ ๊ฒ์ด๋ค. ๊ณต๊ฐ ๋ณต์ก๋ ์ญ์ O(M) ์ด๋ค.