Domanda

I run this code:

public static void main(String[] args) throws Exception {
        boolean a = false;
        boolean b = true;
        xor(a,a);
        xor(a,b);
        xor(b,a);
        xor(b,b);
    }

    public static void xor(boolean a , boolean b){
        System.out.println(a + "\t" + b + "\t" + (a != b));
    }

and got this output :

false   false   false
false   true    true
true    false   true
true    true    false

UPDATE as you know nand truth-table is :

false   false   true
false   true    true
true    false   true
true    true    false

how to return nand only using = or != operators without conditional || and &&?

È stato utile?

Soluzione 2

Implementing nand without && and ||?

Try:

a ? !b : true;

As in:

public static void nand(boolean a , boolean b){
    System.out.println(a + "\t" + b + "\t" + (a ? !b : true));
}

Altri suggerimenti

Basically because false == false returns true. False is not not equal to false, because false is equal to false.

If you are familiar with binary operations: it is like the binary XOR operation

1 XOR 0 = 1
1 XOR 1 = 0
0 XOR 1 = 1
0 XOR 0 = 0 << this is false != false

edit: for the NAND:

a ? !b : true;

a is evaluated, if a is true NOT b is the result, so if b is false, the result will be true and if b is true, the result will be false. In case of a being false the result is always true.

use this function it is the implementation of nand gate

public boolean nand(boolean input1, boolean input2){
    return !(input1 && input2);
}

Well, here's one way...

return String.format("%b%b", a, b).length() != 8; // only "truetrue" has length 8

Of course internally String.format will do a lot of things you forbid in the question...


Here's another way, which uses if instead of conditional, if your only condition is not using other operators:

if (a == false) return true; // (a==false && b==false) || (a==false && b==true)
if (b == false) return true; // (a==true && b==false)
return false;                // (a==true && b==true)

However, NAND does have two independent inputs, which you need to somehow test and combine: a is not true and b is not true. There's no way to get around this being two conditions, you can only obfuscate the fact with different tricks or use library functions in different ways to push this out of your own code.


Third way, in C you could do this: return (int)a + (int)b != 2; or other similar operations on booleans interpreted as integers, but casting booleans to integers is not allowed in Java so for equivalent code you'd have to use (for example) ?: operator to convert boolean to integer. You could of course wrap this in a method, so then in java you could have return myBoolToInt(a) + myBoolToInt(b) != 2;, if just hiding the operation is ok, and you'd be ok with useing +...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top