知之者 不如好之者, 好之者 不如樂之者

기계처럼 살지 말고, 즐기는 인간이 되자

Code/LeetCode

[LeetCode] 67. Add Binary (Easy/Python)

코방코 2022. 9. 8. 18:39
728x90
 

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

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.

 

728x90
반응형