Code Explanation
- Instance of
MyMath
: Creates an instance ofMyMath
calledmath
. - Tests for
isOdd
: UsesMyMath.checker
with theisOdd
operation to check ifnum1
andnum2
are odd. - Tests for
isPrime
: UsesMyMath.checker
with theisPrime
operation to check ifnum1
andnum2
are prime. - Tests for
isPalindrome
: UsesMyMath.checker
with theisPalindrome
operation to check ifnum3
andnum1
are palindromic numbers.
Each of these test cases should print true
or false
based on the conditions of the number.
package tests;
import java.io.*;
import java.util.*;
interface PerformOperation {
boolean check(int a);
}
class MyMath {
public static boolean checker(PerformOperation p, int num) {
return p.check(num);
}
public PerformOperation isOdd() {
return (int num) -> num % 2 != 0;
}
public PerformOperation isPrime() {
return (int num) -> {
for(int i = 2; i * i <= num; i++) {
if(num % i == 0) {
return false;
}
}
return true;
};
}
public PerformOperation isPalindrome() {
return (int num) -> {
String original = Integer.toString(num);
String reversed = new StringBuilder(original).reverse().toString();
return original.equals(reversed);
};
}
}
public class Solution {
public static void main(String[] args) {
MyMath math = new MyMath();
int num1 = 7;
int num2 = 10;
int num3 = 121;
// Testing if the number is odd
System.out.println(num1 + " is odd? " + MyMath.checker(math.isOdd(), num1)); // true
System.out.println(num2 + " is odd? " + MyMath.checker(math.isOdd(), num2)); // false
// Testing if the number is prime
System.out.println(num1 + " is prime? " + MyMath.checker(math.isPrime(), num1)); // true
System.out.println(num2 + " is prime? " + MyMath.checker(math.isPrime(), num2)); // false
// Testing if the number is palindrome
System.out.println(num3 + " is palindrome? " + MyMath.checker(math.isPalindrome(), num3)); // true
System.out.println(num1 + " is palindrome? " + MyMath.checker(math.isPalindrome(), num1)); // false
}
}
Leave a Reply