How can I make the user type a positive integer and display the sum of their example digits : 505 = 5+0+5 =10

Asked

Viewed 29 times

-2

Let soma Let num1

num1 = prompt("Enter a positive number") if(num1 < 0){ console.log("Error you tried to make a negative number account") } Else if (num1 > 0){

}

  • Successively use the %operator, rest of the division or module, along with division (Math.floor).

1 answer

0


John, as the result of prompt is a string (a text), you can use regular expressions to obtain the numbers present. A character class "digit" represents all 10 numerical digits.

In order for this regular expression to work as desired, you need to include the flag "g", because "with this flag, the search searches for all correspondence, since, without it, only the first match is returned" (extracted from the link on flag). Besides, we won’t be using any quantifier, since the goal is to get each number individually.

Understood this, we can apply the regular expression in the input using the method match, which results in a vector.

let entrada = prompt("Digite um número positivo");

if (entrada < 0) {
    console.error("Você tentou fazer uma conta com número negativo")
} else {
    let numeros = entrada.match(/\d/g);
    console.log(numeros);
}

With the vector containing the numbers typed, we can traverse it to add each present number.

let entrada = prompt("Digite um número positivo");

if (entrada < 0) {
  console.error("Você tentou fazer uma conta com número negativo")
} else {
  let numeros = entrada.match(/\d/g);
  let soma = 0;
  
  for(let numero of numeros) {
    soma += parseInt(numero);
  }
  
  alert("A soma é igual a " + soma);
}

Notice that we use the parseint function, as the numbers typed are obtained as string. Then we display an alert with the result of the sum.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.