0

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));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 3
    Did you know there's built-in functions for that? `num.toString(2)` and `parseInt(binary, 2)`. – Cerbrus Oct 19 '22 at 14:38
  • 1
    The code shown definitely doesn't return `undefined`. – T.J. Crowder Oct 19 '22 at 14:38
  • unsure how this is returning undefined. Can you show how you are using it that it is undefined? – epascarello Oct 19 '22 at 14:38
  • 1
    @Cerbrus - They did say "exercise," so presumably they're not supposed to use that. – T.J. Crowder Oct 19 '22 at 14:38
  • Does this answer your question? [How do I convert an integer to binary in JavaScript?](https://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript) – Torben Oct 19 '22 at 14:38
  • Heck, if it's not explicitly specified, I'd rather not reinvent the wheel :D – Cerbrus Oct 19 '22 at 14:39
  • 1
    I bet the `undefined` thing is this: https://stackoverflow.com/questions/14633968/chrome-firefox-console-log-always-appends-a-line-saying-undefined As you can see from the Stack Snippet I copied your code into, your function doesn't actually return `undefined`, it returns a string. (A correct one, for the input I tried.) – T.J. Crowder Oct 19 '22 at 14:39
  • apparently I only needed to try with the console.log Thank you very much! I will also explore the integrated functions that you mention to learn more about the subject – Esteban Descouvieres Oct 19 '22 at 15:11

0 Answers0