ipengxh
V2EX  ›  算法

茴字有多少种写法?(怎么判断一个整数是否为偶数)

  •  
  •   ipengxh · Sep 14, 2020 · 2668 views
    This topic created in 2088 days ago, the information mentioned may be changed or developed.

    以 JS 为例,目前想到的有以下几种:

    • 正经解法:
    return !(num % 2)
    
    • 不正经解法:
    return /^\d*[24680]$/.test(num) // 或者 !/^\d*\.5$/.test(num/2)
    
    return !(num & 1) // 或者 ~num & 1
    
    return num >> 1 << 1 == num
    

    还有什么骚操作?

    Supplement 1  ·  Jan 24, 2022

    递归写法:

    function isEven(n) {
        return n == 0 ? true : (n == 1 ? false: isEven(Math.abs(n - 2)));
    }
    

    异或写法:

    return (n ^ 1) == n + 1;
    7 replies    2022-01-24 18:53:39 +08:00
    shintendo
        1
    shintendo  
       Sep 14, 2020   ❤️ 1
    npm install is-even
    BingoXuan
        2
    BingoXuan  
       Sep 14, 2020
    好像直接看二进制的话,1 的 bit 必定为 1
    BingoXuan
        3
    BingoXuan  
       Sep 14, 2020
    @BingoXuan
    脑抽了,1 的 bit 必定为 0 。lz 的不正经解法 2 就是了。
    ipengxh
        4
    ipengxh  
    OP
       Sep 14, 2020
    0x11901
        5
    0x11901  
       Sep 14, 2020
    @shintendo 正解
    pushback
        6
    pushback  
       Sep 14, 2020
    温两碗酒,要一碟茴香豆!
    ipengxh
        7
    ipengxh  
    OP
       Jan 24, 2022
    又想起来了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3332 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 11:59 · PVG 19:59 · LAX 04:59 · JFK 07:59
    ♥ Do have faith in what you're doing.