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

277
Vistas
How to get String , starting from 1 and ending at n?

How to do that, When user inputs n=4 then it should generate a string like str="1234"?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You can use a simple loop for example :

int n = 4;
String str = "";
for (int i = 1; i <= n; i++) {
    str+=i;
}

can we directly get int= 1234

In this case you can parse it like this :

int result = Integer.parseInt(str);

If you want to avoid this and get int from the begging you can use :

int n = 4;
int result = 0;
for (int i = 1; i <= n; i++) {
    result *= 10;
    result += i;
}
over 4 years ago · Santiago Trujillo Denunciar

0

int n = 10;
StringBuffer s = new StringBuffer();
for(int i=1;i<=n;i++){
s = s.append(i); 
}
System.out.println(s.toString());
over 4 years ago · Santiago Trujillo Denunciar

0

Note: Do not use String concatenation in for, instead it use StringBuilder.

Take a look at this question.

In your case n is a small value and because it is not so important. If n has a big value it will be a vast of memory.

Java 8 way

int n = 4;

StringBuilder sb = new StringBuilder();
IntStream.rangeClosed(1, n).forEach(sb::append);
String str = sb.toString();

Java 7 way

int n = 4;

StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
    sb.append(i);
}
String str = sb.toString();
over 4 years ago · Santiago Trujillo 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