Skip to content

Latest commit

ย 

History

History
78 lines (67 loc) ยท 2.58 KB

Add_Binary.md

File metadata and controls

78 lines (67 loc) ยท 2.58 KB

๋ฌธ์ œ

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) ์ด๋‹ค.