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

274
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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