題目描述

這個題目將會測試您對Lambda表示式的理解程度。



撰寫以下方法,它們皆會回傳一個Lambda表示式:

checkEvenOdd():這個Lambda表示式必須要回傳一個數字是否為偶數或是奇數。如果是偶數,回傳1;如果是奇數,回傳0。
checkPrime():這個Lambda表示式必須要回傳一個數字是否為質數或是複合數。如果是質數;回傳0,如果是複合數,回傳1。
checkPalindrome():這個Lambda表示式必須回傳一個數字是否為回文。如果是回文,回傳0;如果不是回文,回傳1。

原題網址

輸入格式

不需處理。

輸出格式

不需處理。

解題概念

由於要計算質數、回文等比較複雜的邏輯,因此先實作出isPrime和isPalindrome方法。接著實作checkEvenOdd、checkPrime和checkPalindrome方法,回傳performOperation型態的物件。由於performOperation是個Function Interface,因此可以直接用Lambda表示式來實作performOperation介面。

參考答案

import java.io.*;
import java.util.*;

interface performOperation {

    int check(int a);
}

class Math {

    public static int checker(performOperation p, int num) {
        return p.check(num);
    }

    private static boolean isPrime(int n) {
        if(n == 2){
            return true;
        }
        if (n < 2 || n % 2 == 0) {
            return false;
        }
        int nn = (int) java.lang.Math.sqrt(n);
        for (int i = 3; i <= nn; i += 2) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    private static boolean isPalindrome(int n) {
        final char[] c = String.valueOf(n).toCharArray();
        final int length = c.length;
        final int centerIndex = length / 2;
        for (int i = 0; i < centerIndex; ++i) {
            if (c[i] != c[length - 1 - i]) {
                return false;
            }
        }
        return true;
    }

    public static performOperation checkEvenOdd() {
        return a -> a % 2 == 0 ? 0 : 1;
    }

    public static performOperation checkPrime() {
        return a -> isPrime(a) ? 0 : 1;
    }

    public static performOperation checkPalindrome() {
        return a -> isPalindrome(a) ? 0 : 1;
    }
}

public class Solution {

    public static void main(String[] args) throws IOException {
        Math ob = new Math();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());
        performOperation op;
        int ret = 0;
        String ans = null;
        while (T-- > 0) {
            String s = br.readLine().trim();
            StringTokenizer st = new StringTokenizer(s);
            int ch = Integer.parseInt(st.nextToken());
            int num = Integer.parseInt(st.nextToken());
            if (ch == 1) {
                op = ob.checkEvenOdd();
                ret = ob.checker(op, num);
                ans = (ret == 0) ? "EVEN" : "ODD";
            } else if (ch == 2) {
                op = ob.checkPrime();
                ret = ob.checker(op, num);
                ans = (ret == 0) ? "PRIME" : "COMPOSITE";
            } else if (ch == 3) {
                op = ob.checkPalindrome();
                ret = ob.checker(op, num);
                ans = (ret == 0) ? "PALINDROME" : "NOT PALINDROME";

            }
            System.out.println(ans);
        }
    }

}