You've successfully subscribed to The Poor Coder | Hackerrank Solutions
Great! Next, complete checkout for full access to The Poor Coder | Hackerrank Solutions
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Hackerrank Java Lambda Expressions Solution

Hackerrank Java Lambda Expressions Solution

Beeze Aal
Beeze Aal

.MathJax_SVG_LineBox {display: table!important} .MathJax_SVG_LineBox span {display: table-cell!important; width: 10000em!important; min-width: 0; max-width: none; padding: 0; border: 0; margin: 0}

This Java 8 challenge tests your knowledge of Lambda expressions!

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

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

Input Format

Input is handled for you by the locked stub code in your editor.

Output Format

The locked stub code in your editor will print  lines of output.

Sample Input

The first line contains an integer,  (the number of test cases).

The  subsequent lines each describe a test case in the form of  space-separated integers:
The first integer specifies the condition to check for ( for Odd/Even,  for Prime, or  for Palindrome). The second integer denotes the number to be checked.

5
1 4
2 5
3 898
1 3
2 12

Sample Output

EVEN
PRIME
PALINDROME
ODD
COMPOSITE

Solution in java8

Approach 1.

	PerformOperation isOdd(){
		return x -> (x % 2)==1;
	}

	PerformOperation isPrime(){
		return p -> {if(p<3)return true;if((p % 2)==0)return false;for(int i=3;i<Math.sqrt(p);i+=2)if((p % i)==0)return false;return true;}; 
	}

	PerformOperation isPalindrome(){
		return p -> {String pS=((Integer)p).toString();int n=pS.length();for(int i=0;i<n/2;i++)if(pS.charAt(i) != pS.charAt(n-1-i))return false;return true;};
	}
}

Approach 2.

   // Write your code here
    
    public PerformOperation isOdd() {
        return (int a) -> a % 2 != 0;
    }

    public PerformOperation isPrime() {
        return (int a) -> java.math.BigInteger.valueOf(a).isProbablePrime(1);
    }

    public PerformOperation isPalindrome() {
        return (int a) -> Integer.toString(a).equals( new StringBuilder(Integer.toString(a)).reverse().toString() );
    }

    
    
}

Approach 3.

   // Write your code here
    public static PerformOperation isOdd(){
        return (int a) -> a % 2 != 0;
    }
    
    public static PerformOperation isPrime(){
        return (int a) -> java.math.BigInteger.valueOf(a).isProbablePrime(1);
    }
    
    public static PerformOperation isPalindrome(){
        return (int a) ->  Integer.toString(a).equals( new StringBuilder(Integer.toString(a)).reverse().toString() );
    }
}