javascript – Next number without repeating digits

Question:

I am doing this function in which a number is passed per parameter; If it has any repeated digits then look for the next closest higher number that does not have the same digits.

Ex: proximoNumero(2002) -> return 2013

Ex: proximoNumero(1001) -> return 1023

Ex: proximoNumero(899) -> return 901

 function proximoNumero(numero){ numero = (numero+1).toString().split('') for(let i=0; i<numero.length-1; i++){ for(let j=i+1; j<numero.length; j++){ if(numero[i] === numero[j]){ console.log(`${numero} se repite ${numero[i]}`); proximoNumero(Number(numero.join(''))) } } } return numero.join('') } console.log(proximoNumero(1001));

My function is doing something similar but I don't understand why once it is called recursively with a number without repeated characters, it returns the first number that is passed by parameter

Answer:

You are missing a return when making the recursive call that breaks (exits) the double loop:

 function proximoSinRepetidos(numero){ numero = (numero+1).toString().split('') for(let i=0; i<numero.length-1; i++){ for(let j=i+1; j<numero.length; j++){ if(numero[i] === numero[j]){ console.log(`${numero} se repite ${numero[i]}`); //Aquí te faltaba "return" delante return proximoSinRepetidos(Number(numero.join(''))); } } } return numero.join('') } console.log(proximoSinRepetidos(1001));
Scroll to Top