Check if at least two out of three booleans are true

后端 未结 30 1866
自闭症患者
自闭症患者 2020-11-28 16:47

An interviewer recently asked me this question: given three boolean variables, a, b, and c, return true if at least two out of the three are true.

My solution follow

30条回答
  •  再見小時候
    2020-11-28 17:28

    As an addition to @TofuBeer TofuBeer's excellent post, consider @pdox pdox's answer:

    static boolean five(final boolean a, final boolean b, final boolean c)
    {
        return a == b ? a : c;
    }
    

    Consider also its disassembled version as given by "javap -c":

    static boolean five(boolean, boolean, boolean);
      Code:
        0:    iload_0
        1:    iload_1
        2:    if_icmpne    9
        5:    iload_0
        6:    goto    10
        9:    iload_2
       10:    ireturn
    

    pdox's answer compiles to less byte code than any of the previous answers. How does its execution time compare to the others?

    one                5242 ms
    two                6318 ms
    three (moonshadow) 3806 ms
    four               7192 ms
    five  (pdox)       3650 ms
    

    At least on my computer, pdox's answer is just slightly faster than @moonshadow moonshadow's answer, making pdox's the fastest overall (on my HP/Intel laptop).

提交回复
热议问题