題目
在一些腳本語言如PHP,存在一個邏輯運算符(例如&&,||,and,or,等)中有一種是“異或”運算符。如果兩個表達式中只有一個為真,則返回true ,否則返回false。例如:
false xor false == false // since both are false
true xor false == true // exactly one of the two expressions are true
false xor true == true // exactly one of the two expressions are true
true xor true == false // Both are true. "xor" only returns true if EXACTLY one of the two expressions evaluate to true.
任務
由于我們無法在Javascript中定義關(guān)鍵字(好吧,至少我不知道該怎么做),你的任務是定義一個函數(shù)xor(a, b),其中a和b是要評估的兩個表達式。您的xor函數(shù)應具有上述行為,如果兩個表達式中只有一個計算為true,則返回true,否則返回false。
測試用例:
import static org.junit.Assert.*;
import org.junit.Test;
public class XORTest {
private static void testing(boolean actual, boolean expected) {
assertEquals(expected, actual);
}
@Test
public void testBasic() {
System.out.println("Testing basics.");
testing(XOR.xor(false, false), false);
testing(XOR.xor(true, false), true);
testing(XOR.xor(false, true), true);
testing(XOR.xor(true, true), false);
}
@Test
public void testNested() {
System.out.println("Testing nested calls.");
testing(XOR.xor(false, XOR.xor(false, false)), false);
testing(XOR.xor(XOR.xor(true, false), false), true);
testing(XOR.xor(XOR.xor(true, true), false), false);
testing(XOR.xor(true, XOR.xor(true, true)), true);
testing(XOR.xor(XOR.xor(false, false), XOR.xor(false, false)), false);
testing(XOR.xor(XOR.xor(false, false), XOR.xor(false, true)), true);
testing(XOR.xor(XOR.xor(true, false), XOR.xor(false, false)), true);
testing(XOR.xor(XOR.xor(true, false), XOR.xor(true, false)), false);
testing(XOR.xor(XOR.xor(true, true), XOR.xor(true, false)), true);
testing(XOR.xor(XOR.xor(true, XOR.xor(true, true)), XOR.xor(XOR.xor(true, true), false)), true);
}
}
解題
My
Java有異或^運算符。注釋的方法也可以。
public class XOR {
public static boolean xor(boolean a, boolean b) {
// return ( !a && b) ||(a && !b);
return a^b;
}
}
Other
聰明的:
public class XOR {
public static boolean xor(boolean a, boolean b) {
return a!=b;
}
}
public class XOR {
public static boolean xor(boolean a, boolean b) {
return !(a==b);
}
}
后記
還好Java有異或^。