Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
Codwars: matriz a valor único +1

Dada una matriz de enteros de cualquier longitud, devuelva una matriz que tenga 1 agregado al valor representado por la matriz.

la matriz no puede estar vacía, solo se permiten números enteros no negativos de un solo dígito

Devuelva nil (o el equivalente de su idioma) para entradas no válidas.

Ejemplos Por ejemplo, la matriz [2, 3, 9] es igual a 239, agregar uno devolvería la matriz [2, 4, 0].

Mi código hasta ahora:

 function upArray(arr){ let i = parseInt(arr.join('')) + 1; return arr.some(e => typeof e !== 'number' || e < 0) ? null : i .toString() .split('') .map(e => parseInt(e)); };

Parece pasar la prueba más básica, pero falla con entradas más grandes. ¿Dónde me he equivocado?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Al igual que ha convertido la matriz en un número, debe volver a convertir el número en una matriz.

 function upArray(arr){ let i = parseInt(arr.join('')) + 1; return i.toString().split('').map(x => parseInt(x)); }; console.log(upArray([2,3,9]));

about 4 years ago · Juan Pablo Isaza Report

0

Su código no funcionará si la longitud de la matriz es superior a 100k...

El tipo de número de javascript o cualquier idioma no es lo suficientemente grande para manejarlo.

Es mejor si calculamos el último elemento con 1. Si el resultado es mayor que agradable ( < 10 ), continuamos calculando el siguiente elemento con 1 y asignamos el valor actual a 0. Si el resultado es menor o igual a 9, simplemente asigne el resultado a bucle de corriente y de salida.

Luego imprimimos la matriz final como resultado:

pseudocódigo:

 for i from: n-1:0 result = arr[i] + 1; if(result < 10) : arr[i] = result; exit loop;// no need to continue calculate else: arr[i] = 0; endif; endfor;

Puede unirse a la matriz final como una cadena.

about 4 years ago · Juan Pablo Isaza Report

0

Esta es probablemente la solución más rápida (en cuanto al rendimiento), además, no hay necesidad de lidiar con BigInt, NaN o Infinity:

 function upArray(arr) { if (!isInputIsNonEmptyArray(arr)) { return null; } const isNumber = num => typeof num === 'number'; const isIntSingleDigit = num => Number.isInteger(num) && num >= 0 && num <10; let resultArr = []; let i = arr.length; let num; while (i-- > 0) { num = arr[i]; if (!isNumber(num) || !isIntSingleDigit(num)) { return null; } if (num === 9) { resultArr[i] = 0; if (i === 0) { //means we're in the msb/left most digit, so we need to insert 1 to the left resultArr.unshift(1); break; //you can leave it out really, as the next check in the while will fail anyway } } else { resultArr[i] = num + 1; //No more + 1 should be made, just check for validity //of the rest of the input and copy to the result arr while (--i > -1) { num = arr[i]; if (!isNumber(num) || !isIntSingleDigit(num)) { return null; } resultArr[i] = arr[i]; } break; } } return resultArr; function isInputIsNonEmptyArray(arr) { return Array.isArray(arr) && arr.length > 0; } }

Si el argumento de entrada no es una matriz o una matriz vacía, o si encuentra un elemento no válido durante el ciclo while principal, devuelve un valor nulo.

En el bucle while principal, va desde el elemento más a la derecha (lsd) y le agrega 1 (o inserta 0 si el número es 9) hasta el dígito más a la izquierda.

Si se incrementa un número que es menor que 9, no es necesario incrementar más (este es el ciclo while en la cláusula else).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!