Above is the link to the problem.
Given two binary strings a and b, return their sum as a binary string.
Example :
Input: a = "1010", b = "1011"
Output: "10101"
I solved this problem by writing the below code.
If both digits of the same digit are 1, the carry is bound to occur.
And that carry has to be added when calculating the next digit.
I wrote the code using this.
However, I thought I had to operate with a string type to calculate the result.
Looking at the answers provided by other people, it seems that it was possible to submit an answer that was solved using the "bin" function like this.
a="1010"
b="1011"
print(int(a,2)) #result = 10
print(bin(int(a, 2) + int(b, 2))[:]) #result = 0b10101
print(bin(int(a, 2) + int(b, 2))[2:]) #result = 10101
int(a,2) calculate the decimal number of "a" which is the binary number (because of 2).
And bin function changes the number to a binary number like 0b~~.
If we print except the first 2 digits, we can get the answer.
This code gets the top 41.12% of time efficiency and the top 74.10% of space efficiency.
'Code > LeetCode' 카테고리의 다른 글
[LeetCode] 88. Merge Sorted Array (Easy/Python) (0) | 2022.09.17 |
---|---|
[LeetCode] 70. Climbing Stairs (Easy/Python) (0) | 2022.09.15 |
[LeetCode] 58. Length of Last Word (Easy/Python) (0) | 2022.09.07 |
[LeetCode] 48. Rotate Image (Medium/Python) (0) | 2022.09.05 |
[LeetCode] 35. Search Insert Position (Easy/Python) (0) | 2022.09.03 |