Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

191
Vistas
return statement in function that convert decimal to binary numbers

I'm trying to understand how to use functions in JS.

This code converting decimal numbers to binary numbers:

for (j = 13; j <= 16; j++) {
  res = ""
  number = j

  while (number > 0) {
    res = res + number % 2
    number = Math.floor(number / 2)
  }

  len = res.length

  rev=""

  for (i = 1; i <= len; i++) {
    rev = rev + res[res.length - i]
  }
  
  console.log(rev)
}

but when I'm trying to put this code into a function, the function returns only the first or the last value. What am I doing wrong?

function f(min, max) {
  for (j = min; j <= max; j++) {
    res = ""
    number = j
    
    while (number > 0) {
      res = res + number % 2
      number = Math.floor(number / 2)
    }

    len = res.length

    rev=""

    for (i = 1; i <= len; i++) {
      rev = rev + res[res.length-i]     
    }  
  }
  return rev
}

console.log(f(13,15))
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You have to store the result of each iteration in array.

function f(min, max) {
  const results = []
  for (j = min; j <= max; j++) {
    res = ""
    number = j
    
    while (number > 0) {
      res = res + number % 2
      number = Math.floor(number / 2)
    }

    len = res.length

    rev=""

    for (i = 1; i <= len; i++) {
      rev = rev + res[res.length-i]     
    }
    
    results.push(rev)
  }
  return results
}

console.log(f(13,15))

Also you should declare your variables in JavaScript, because not doing that can lead to bugs https://www.geeksforgeeks.org/what-happen-when-we-directly-assign-the-variable-without-declaring-it-in-javascript/

about 4 years ago · Juan Pablo Isaza Denunciar

0

You need a variable for gathering all intermediate results.

You could take declarations for all variables.

function f(min, max) {
    const result = [];
    for (let j = min; j <= max; j++) {
        let number = j,
            temp = "";
        while (number > 0) {
            temp += number % 2;
            number = Math.floor(number / 2);
        }
        result.push(temp);
    }
    return result;
}

console.log(f(13, 15));

about 4 years ago · Juan Pablo Isaza Denunciar

0

You should divide your code into to functions

one that turn a number in binary string (I also included the existing js version)

and one that create a list of element between min and max and iterate onto them

const toBin = n => n.toString(2)

const customToBin = n => {
  const res = []
  let number = n
  while (number > 0) {
    res.push(number % 2)
    number = Math.floor(number / 2)
  }
  return res.reverse().join('')
}

const createInterval = (min, max) => Array(max - min + 1).fill(min).map((_, i) => min + i)

const f = (min, max) => createInterval(min, max).map(customToBin)


console.log(f(13, 16))

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda