|
| 1 | +# Challenge Description and Solution |
| 2 | + |
| 3 | +## English Version |
| 4 | + |
| 5 | +### Challenge Description |
| 6 | +Create a function that, given an integer, returns the sum of its digits. Make sure to handle negative numbers and the special case of zero. |
| 7 | + |
| 8 | +### Code Explanation |
| 9 | +The `sumOfDigits` function first converts the number to its absolute value to handle negative numbers. If the number is zero, it returns 0. Then, it uses a `while` loop to sum each digit of the number, obtaining the least significant digit with the modulo operator `%` and removing it with integer division. |
| 10 | + |
| 11 | +### Relevant Code Snippet |
| 12 | + |
| 13 | +```javascript |
| 14 | +function sumOfDigits(n) { |
| 15 | + n = Math.abs(n); |
| 16 | + if (n === 0) { |
| 17 | + return 0; |
| 18 | + } |
| 19 | + let total = 0; |
| 20 | + while (n > 0) { |
| 21 | + total += n % 10; |
| 22 | + n = Math.floor(n / 10); |
| 23 | + } |
| 24 | + return total; |
| 25 | +} |
| 26 | +``` |
| 27 | + |
| 28 | +### Example Usage |
| 29 | + |
| 30 | +```javascript |
| 31 | +const testValues = [0, 123, -456, 7890]; |
| 32 | +testValues.forEach(val => { |
| 33 | + console.log(`Sum of digits of ${val}: ${sumOfDigits(val)}`); |
| 34 | +}); |
| 35 | +``` |
| 36 | + |
| 37 | +--- |
| 38 | + |
| 39 | +## Versión en Español |
| 40 | + |
| 41 | +### Descripción del Reto |
| 42 | +Crea una función que, dado un número entero, retorne la suma de sus dígitos. Asegúrate de manejar números negativos y el caso especial del cero. |
| 43 | + |
| 44 | +### Explicación del Código |
| 45 | +La función `sumOfDigits` primero convierte el número a su valor absoluto para manejar números negativos. Si el número es cero, retorna 0. Luego, utiliza un bucle `while` para sumar cada dígito del número, obteniendo el dígito menos significativo con el operador módulo `%` y eliminándolo con la división entera. |
| 46 | + |
| 47 | +### Fragmento de Código Relevante |
| 48 | + |
| 49 | +```javascript |
| 50 | +function sumOfDigits(n) { |
| 51 | + n = Math.abs(n); |
| 52 | + if (n === 0) { |
| 53 | + return 0; |
| 54 | + } |
| 55 | + let total = 0; |
| 56 | + while (n > 0) { |
| 57 | + total += n % 10; |
| 58 | + n = Math.floor(n / 10); |
| 59 | + } |
| 60 | + return total; |
| 61 | +} |
| 62 | +``` |
| 63 | + |
| 64 | +### Ejemplo de Uso |
| 65 | + |
| 66 | +```javascript |
| 67 | +const testValues = [0, 123, -456, 7890]; |
| 68 | +testValues.forEach(val => { |
| 69 | + console.log(`Suma de dígitos de ${val}: ${sumOfDigits(val)}`); |
| 70 | +}); |
0 commit comments