ฟังก์ชันที่รับ 0 ส่ง 1, รับ 1 ส่ง 0 โดยไม่ใช้ if (?)

http://www.youtube.com/watch?v=-L7_qVJ6lYo

public class Test {
  public static int f1(int n) {
    return 1 - n;
  }

  public static int f2(int n) {
    return (n + 1) % 2;
  }

  public static int f3(int n) {
    return n ^ 1;
  }

  public static int f4(int n) {
    return 1 >> n;
  }
  
  public static int f5(int n) {
    return (int) Math.ceil(0.5 - n);
  }

  public static int f6(int n) {
    return (int) Math.abs(n - 1);
  }

  public static int f7(int n) {
    return 2 - (int) Math.pow(2, n);
  }
  public static int f8(int n) {
    int[] a = {1, 0};
    return a[n];
  }

  public static int f9(int n) {
    int[] a = {-1, 0};
    return java.util.Arrays.binarySearch(a, -n);
  }

  public static int f10(int n) {
    try {
      n = 1 / n;
      return 0;
    } catch (Exception ex) {
      return 1;
    }
  }

  public static void main(String[] args) {
    if (f5(0) == 1 && f5(1) == 0)
      System.out.println("correct");
    else
      System.out.println("INcorrect");
  }
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s