Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
How to add two integers in one line

Hello im new to java and in my class my prof wants us to create a program that will compute the sum of two numbers. (Use methods) For example: Input an integer: 95 //Expected Output: The sum is 14 //(9+5=14)

im really lost on this one because i really don't know how to do this please help

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

From an algorithm point of view, the easiest way would be to:

  • convert the integer to a string
  • iterate the characters
  • convert each character back to an int
  • do the sum

In "Modern" java:

String.valueOf(test).chars().mapToLong(c -> Long.parseLong("" + (char) c)).reduce(Long::sum).getAsLong()

In older java:

int test = 95;
long sum = 0;
for (char c : String.valueOf(test).toCharArray()) {
    sum += Integer.parseInt(String.valueOf(c));
}
System.out.println(sum);

In javascript:

let sum = 0
for (let c of String(test)) {
    sum += parseInt(c)
}
console.log(sum)
about 4 years ago · Juan Pablo Isaza Relatório

0

If you use Java you can use this code:

int num = 95;
int sum = 0;

while (0 != num) {
    // add the last digit of the given number to the sum
    sum = sum + (num % 10);
    // remove the last digit of the given number
    num = num / 10;
}

System.out.println(sum);

(The code in JavaScript is very similar)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda