반응형
Add Binary
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
1 <= a.length, b.length <= 104aandbconsist only of'0'or'1'characters.- Each string does not contain leading zeros except for the zero itself.
class Solution:
def addBinary(self, a: str, b: str) -> str:
dec_a = dec_b = 0
a = reversed(a)
b = reversed(b)
cnt_a = cnt_b = 0
for i in a :
i = int(i)
dec_a += (2 ** cnt_a) * i
cnt_a += 1
for i in b :
i = int(i)
dec_b += (2 ** cnt_b) * i
cnt_b += 1
dec_a += dec_b
return bin(dec_a)[2:]
이진수를 십진수로 바꾸고 두 수를 합한 다음, 다시 이진수로 표현하는 문제이다. 그냥 진행할 경우에는 길이를 하나씩 빼가면서 계산하면 된다. 저는 뒤집은 다음 하나씩 올라가면서 계산함.
반응형
'알고리즘 스터디' 카테고리의 다른 글
| [Leetcode/파이썬] 219. Contains Duplicate II (0) | 2026.02.12 |
|---|---|
| [Leetcode/파이썬] 15. 3Sum (0) | 2026.02.08 |
| [Leetcode/파이썬] 122. Best Time to Buy and Sell Stock II (0) | 2026.02.08 |
| [Leetcode/파이썬] 189. Rotate Array (0) | 2026.02.01 |
| [Leetcode/파이썬] 54. Spiral Matrix (0) | 2026.02.01 |