Detect digit repetition in Java

Asked

Viewed 204 times

-3

I need to make a program that reads a positive integer N. After reading this number, the program must evaluate if there are repeated digits in the number.

For example: in 234571 there are no repeated digits. another example: in 7656 there are repeated digits.

It has to be done in java and if possible without using vector, my doubt is how to do this check because it can not type a number with equal digits, understood?

package lista01;

import java.util.Scanner;

public class Ex08 {

public static void main(String[] args) {
    Scanner ler = new Scanner(System.in);

    int num = 0, a, b, c, d, contarDigitos = 0;

    System.out.println("Digite um numero de quatro digitos diferentes");
    num = ler.nextInt();

    contarDigitos = (int) (Math.log10(num) + 1);

    if (contarDigitos == 4) {
        d = num / 1000;
        a = (num / 100) % 10;
        b = (num % 100) / 10;
        c = (num % 10) % 10;

        System.out.println("Resultado:" + d + a + b + c);
    } else {
        System.out.println("O numero precisa ter 4 digitos execute novamente!");
    }


   }
}

I don’t know how I’m gonna check if those numbers are different

  • You can do it without using vector?

  • So the message says it needs to be 4 digits, and all different? If yes, you would put these 2 validations, correct?

1 answer

0


Well, I’ve come up with a solution that may not be very efficient, but at least it doesn’t use vector. Since it has only 10 possible digits, you could have 10 variables (which sounds strange and it would be better to use a vector of 10 positions, but anyway) where each one is a flag to know if a certain digit has already appeared. For example, int flag1, int flag2 and so on. Then in a loop you scroll through the digits and see if it matches the flags. If this happens twice you know that the digit has appeared twice.

Browser other questions tagged

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