I am stuck with a javascript exercise in which I must create a function that receives an integer as an argument and converts it to a binary number (as a string)
I tried to create an empty array to hold each digit of the calculation in one position. Then I am doing the calculation with a "do while" loop in which it evaluates if the number is 1, if it is > 1 and it is even, if it is > 1 and it is odd and then divides the input number by 2 (base) . The loop repeats as long as the input number is >= 1 and returns the concatenated array
When I run the code in the browser, it returns undefined...
function DecimalABinario(num) {
var arrayBinario = [];
do {
if (num <= 1) {
arrayBinario.unshift('1');
}
if (num > 1 && num % 2 === 0) {
arrayBinario.unshift('0');
}
if (num > 1 && num % 2 !== 0) {
arrayBinario.unshift('1');
}
num = Math.floor(num / 2);
} while (num >= 1);
return arrayBinario.join('');
}
console.log(DecimalABinario(36));