Checking if two three digit numbers have any of there digits that are the same in Java

Viewed 489

I'm trying to write a program in Java that checks if at least one digit of one of the numbers, matches one digit of the other number. For example, if the two numbers are 238 and 345 it should return a certain string.
So far this is what I have, but it only works properly for the right most digit:

if ((computerGuess/10) == (userGuess/10) || (computerGuess%10) == (userGuess%10) || (computerGuess%10) == (userGuess/10) || (userGuess%10) == (computerGuess/10)) {
                System.out.println("You have won S1000");
                break;
            }
4 Answers

One clean solution would be to convert each number into a set of digits, and then check for overlap:

public Set<Integer> getDigits (int input) {
    Set<Integer> digits = new HashSet<>();
    while (input > 0) {
        digits.add(input % 10);
        input /= 10;
    }

    return digits;
}

int computerGuess = 238;
int userGuess = 345;
Set<Integer> computerDigits = getDigits(computerGuess);
Set<Integer> userDigits = getDigits(userGuess);
computerDigits.retainAll(userDigits);

if (computerDigits.size() > 0) {
    System.out.println("There is an overlap: " + computerDigits.toString());
}

The reason is always you are using "10", either '/10' or '%10'.

The best solution would convert them into string, and check for sub-string.

String computerGuessStr = new String (computerGuess);
String userGuess = new String (userGuess);

for (int i=0;i<computerGuessStr.length();i++){

char computerChar = computerGuessStr.getCharAt(i);

if(userGuess.contains(computerChar)){
//do something
} else {
//do something
}

Something like this?

int computerNumber = 543;
int guess = 238;
List<Integer> numbers = Stream.of(10, 100, 1000).map(n -> guess % n).collect(Collectors.toList());

Stream.of(10,100,1000).map(n -> computerNumber % n).anyMatch(num -> numbers.contains(num));

Another option is the plain old loop. This will work with any length number.

boolean digitMatch(int num1, int num2)
{
    for ( ; num1 > 0; num1 /= 10) {
        // Get a digit from num1
        int digit1 = num1 % 10;
        for (int n2 = num2; n2 > 0; n2 /= 10) {
            // Get a digit from num2
            int digit2 = n2 % 10;
            // compare
            if (digit1 == digit2) return true;
        }
    }
    return false;
}

Note: you need to add a little extra code for negative numbers.

Related