Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda