2021. 3. 14. 10:17ㆍJava programming
Write a method named hasSharedDigit with two parameters of type int.
Each number should be within the range of 10 (inclusive) - 99 (inclusive).
If one of the numbers is not within the range, the method should return false.
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.
public class SharedDigit {
public static boolean hasSharedDigit (int number1, int number2){
if (number1 < 10 || number1 > 99 || number2 < 10 || number2 > 99)
return false;
while (number1 > 0){
int i = number1 % 10;;
int tempNumber2 = number2;
while (tempNumber2 > 0){
int j = tempNumber2 % 10;
if(i == j){
return true;
}
tempNumber2 /= 10;
}
number1 /= 10;
} return false;
}
}
The coding exercise is asking you if your numbers have in common while they're in the range of 10 to 99.
Like I said in the previous session, using 'number % 10' to find the last digit as a single-digit number and 'number / 10' in the while loop for checking the next last digit enables us to compare each digit.
One of the key lessons to learn here is a nested while loop, that is a while loop inside another while statement.
In the nested while loop, one iteration of the outer loop is first executed, after which the inner while loop is executed as once the condtion of the inner loop is satisfied, the proram moves to the next iteration of the outer loop.
Pretty intriguing stuff to challenge.
'Java programming' 카테고리의 다른 글
Coding Exercise 20: Greatest Common Divisor (0) | 2021.03.21 |
---|---|
Coding Exercise 19: Last Digit Checker (0) | 2021.03.15 |
Coding Exercise 17: Even Digit Sum (0) | 2021.03.13 |
Coding Exercise 16: First And Last Digit Sum (0) | 2021.03.12 |
Coding Exercise 15: Number Palindrome (0) | 2021.03.11 |