New to coding, I just thought of an idea of converting decimal numbers to binary so I made this program.
However, while I feel the logic is right, I'm not sure why its not returning a full array of zero's and 1's corresponding to the decimal number that was input.
After I get the array, I plan on doing remainder.join('') to return as one string.
If anyone could share their thoughts that would be great.
Currently it only consoles an array like ['1'] or ['0'].
const getBinary = (num) => {
let remainder = [];
let quotient = Math.floor(num / 2);
while (num != 0) {
if ((quotient * 2) < num) {
remainder.push('1');
} else if ((quotient * 2) === num) {
remainder.push('0');
}
num = Math.floor(num / 2);
return remainder;
}
};
console.log(getBinary(6));
You put the return statement in the while loop so it only loops once. You should place the return statement before the last }. Also, you should update the quotient variable in each loop.
const getBinary = (num) => {
let remainder = [];
let quotient = Math.floor(num / 2);
while (num != 0) {
if ((quotient * 2) < num) {
remainder.push('1');
} else if ((quotient * 2) === num) {
remainder.push('0');
}
num = Math.floor(num / 2);
quotient = Math.floor(num / 2); // added this line
// return remainder; move this line
}
// to there
return remainder;
};
console.log(getBinary(6));