Reputation: 1
Write a method named hasSharedDigit with two parameters of type int.
Numbers are between 10 and 99
The method should return true if there is a digit that appears in both numbers, such as 2 in 12 and 23; otherwise, the method should return false.
I have a solution, but don't quite understand how it works. I need an English explanation.
public class SharedDigit {
public static boolean hasSharedDigit(int numA,int numB){
if((numA<10||numA>99)||(numB<10||numB>99)){
return false;
}
int realNumB=numB;
while(numA>0){
int numADig=numA%10;
while(numB>0){
int numBDig=numB%10;
if(numADig==numBDig){
return true;
}
numB=numB/10;
}
numA=numA/10;
numB=realNumB;
}
return false;
}
}
I don't understand how this code is checking all possibilities of matching numbers
Upvotes: 0
Views: 982
Reputation: 21
Have a look on my correct solution.
public class SharedDigit {
public static boolean hasSharedDigit (int one, int two) {
int modulusOne = one % 10;
int modulusTwo = two % 10;
int divisionOne = one / 10;
int divisionTwo = two / 10;
if ((one < 10 || one > 99) || (two < 10 || two > 99)) {
return false;
} else if (one == two){
return true;
} else if (modulusOne == modulusTwo){
return true;
} else if (divisionOne == divisionTwo){
return true;
} else if (divisionOne == modulusTwo){
return true;
} else if (divisionTwo == modulusOne){
return true;
} else {
return false;
}
}
}
Upvotes: 0
Reputation: 140633
This here:
while(numA>0){
int numADig=numA%10;
uses the modulo operator to "get" the last digit of a number, see here for more information. So this first step gets you the "3" from 13 for example.
Later, you do:
numA=numA/10;
That turns 13 into 1 (int division)! That initial loop condition before ensures that you stop when you did 13 / 10 .. and then 1 / 10.
So this loops turns 13 into 3, then 1, and then stops.
And the same "method" is used to get the digits of the second number. And as soon as you find a digit in both numbers, you can return true.
Otherwise, if you walked trough all digits of the first number, and compared them against all digits in the second number ... no match, return false.
The real answer here, btw: when you do not understand what code does:
Upvotes: 2