소프트웨어에 대한 모든 것

LeetCode 풀기 - 67. Add Binary 본문

알고리즘/LeetCode

LeetCode 풀기 - 67. Add Binary

앤테바 2022. 1. 10. 21:29
반응형

67. Add Binary

https://leetcode.com/problems/add-binary/

 

Add Binary - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1) 직접 계산

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        a = list(map(int, a))
        b = list(map(int, b))
        
        res = ''
        carry = 0
        while a or b or carry:
            if a:
                carry += a.pop()
            if b:
                carry += b.pop()
            
            res += str(carry % 2)
            carry = carry // 2
        return res[::-1]

솔루션2) int(), bin() 함수 사용

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        return bin(int(a, base=2) + int(b, base=2))[2:]

 

반응형
Comments