Taking Values from a range of numbers where the tens n repeat

Asked

Viewed 104 times

0

I would like a way to solve a problem that consists in reading 2 user numbers that will be my start and end ex 10 and 50 and within that range do not show the repeated numbers ex 11,22,33,44.

1 answer

0


You could turn this int for String and so compare your substring or still use a regular expression

Something like this:

int inicio = 0;
int fim = 50;

for (int i = inicio; i < fim; i++) {
  String check = String.valueOf(i);
  if (check.length() > 1) {
    if (check.substring(0, 1).equals(check.substring(1, 2))) {
      System.out.println(i); //mostro os repetidos
    }
  }
}
  • Problem: and when the final value exceeds 100? When checking the value 115, for example, your condition will be true. Generally speaking, how would you work with string without knowing the number of digits of the values?

  • As an example I took the values shown since the question says: problem consisting of reading 2 numbers, but if the input is another maybe you would have to use a regex instead of substring: if(check.matches("^(\\d)\\1+$")){}

  • Note that the question does not limit the possible intervals, so try to increase your answer with a more generic solution.

  • Thank you brother.

Browser other questions tagged

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