每日一練50——Java異或(xor)邏輯運算符(8kyu)

題目

在一些腳本語言如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有異或^。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容