HackerRank Java- Lambda Expressions




Write the following methods that return a lambda expression performing a specified action:

PerformOperation isOdd(): The lambda expression must return true if a number is odd or false if it is even.
PerformOperation isPrime(): The lambda expression must return true if a number is prime or false if it is composite.
PerformOperation isPalindrome(): The lambda expression must return true if a number is a palindrome or false if it is not.



  1. import java.io.*;
  2. import java.util.*;
  3. interface PerformOperation {
  4. boolean check(int a);
  5. }
  6. class MyMath {
  7. public static boolean checker(PerformOperation p, int num) {
  8. return p.check(num);
  9. }
  10. public static PerformOperation isOdd() {
  11. return n -> (n & 1) == 1;
  12. }
  13. public static PerformOperation isPrime() {
  14. return n -> {
  15. if (n < 2) {
  16. return false;
  17. } else if (n == 2) {
  18. return true;
  19. } else if (n % 2 == 0) {
  20. return false;
  21. }
  22. int sqrt = (int) Math.sqrt(n);
  23. for (int i = 3; i <= sqrt; i += 2) {
  24. if (n % i == 0) {
  25. return false;
  26. }
  27. }
  28. return true;
  29. };
  30. }
  31. public static PerformOperation isPalindrome() {
  32. return n -> {
  33. String original = Integer.toString(n);
  34. String reversed = new StringBuilder(Integer.toString(n)).reverse().toString();
  35. return original.equals(reversed);
  36. };
  37. }
  38. }
  39. public class Solution {
  40. public static void main(String[] args) throws IOException {
  41. MyMath ob = new MyMath();
  42. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  43. int T = Integer.parseInt(br.readLine());
  44. PerformOperation op;
  45. boolean ret = false;
  46. String ans = null;
  47. while (T--> 0) {
  48. String s = br.readLine().trim();
  49. StringTokenizer st = new StringTokenizer(s);
  50. int ch = Integer.parseInt(st.nextToken());
  51. int num = Integer.parseInt(st.nextToken());
  52. if (ch == 1) {
  53. op = ob.isOdd();
  54. ret = ob.checker(op, num);
  55. ans = (ret) ? "ODD" : "EVEN";
  56. } else if (ch == 2) {
  57. op = ob.isPrime();
  58. ret = ob.checker(op, num);
  59. ans = (ret) ? "PRIME" : "COMPOSITE";
  60. } else if (ch == 3) {
  61. op = ob.isPalindrome();
  62. ret = ob.checker(op, num);
  63. ans = (ret) ? "PALINDROME" : "NOT PALINDROME";
  64. }
  65. System.out.println(ans);
  66. }
  67. }
  68. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube