--DAY 13--
Hi, I am going to make #100DaysOfCode Challenge. Everyday I will try solve 1 problem from leetcode or hackerrank. Hope you can go with me until end.
Now let's solve problem today:
- Problem: Add binary
- Detail: here
- Idea: check sum of each pair binary number from tail.
- ex: 1010, 1011
- initiate empty string s, one left over = 0;
- 1 + 0 + (oneleftover=0) = 1 -> s=1, oneleftover = 0
- 1 + 1 + (oneleftover=0) = 0 -> s=10, set oneleftover = 1
- 0 + 0 + (oneleftover=1) = 1 -> s=101, set oneleftover = 0
- 1 + 1 + (oneleftover=0) = 0 -> s=1010, set oneleftover = 1
- oneleftover = 1 -> s=10101
- reverse string s : 10101
- My solution (javascript):
var addBinary = function(a, b) {
let binary='',i=a.length-1,j=b.length-1,s=0;
while(i>=0||j>=0||s){
let digit = (+a[i]||0)+(+b[j]||0)+s;
s=Math.floor(digit/2);
binary+=(digit%2);
i--;j--;
}
return binary.split('').reverse().join('');
};
-->If you have better solution or any question, please comment below. I will appreciate.
Top comments (0)