• Kraiden@kbin.earth
    link
    fedilink
    arrow-up
    4
    arrow-down
    8
    ·
    1 day ago

    I’m sorry, but even without knowing about the mod operator, this is inefficient and over engineered. Why have a loop at all?

    fun isEven(n: Int){
        return n == abs(n)
    }
    

    no loop required…

    having said that, I can totally see how that was missed in a high pressure interview. I hate interviews like that!

    edit: Ha ha… isEven…not isPositive… I’m tired. ignore me!

    • lobut@lemmy.ca
      link
      fedilink
      arrow-up
      11
      ·
      edit-2
      1 day ago

      Because the abs(3) == 3 is true and that isn’t even.

      An even number of flips would be true and an odd number of flips would be false which works out.

      I was thinking a bitwise & or converting it to a string and testing if the right most character is 0, 2, 4, 6, 8 would be panic mode solutions too.

      • Kraiden@kbin.earth
        link
        fedilink
        arrow-up
        2
        ·
        22 hours ago

        you might be able to do it with a bitwise op? My track record tonight is not great so I’m not going to comment. Have a look at @ImplyingImplactions comment for a loopless solution

        • UID_Zero@infosec.pub
          link
          fedilink
          English
          arrow-up
          2
          ·
          19 hours ago

          Bitwise and with 0x1. If result is 0, it’s even. Least significant bit is always 1 for odd numbers.

    • ImplyingImplications@lemmy.ca
      link
      fedilink
      arrow-up
      8
      ·
      24 hours ago

      That would be isPositive.

      Without using the modulo operator you’d essentially have to reimplement it. Divide the number by 2 and round down. Multiply that by 2 and then subtract it from the original number.

      isEven(10) results in 10-10==0 (true) whereas isEven(13) results in 13-12==0 (false).

      function isEven(n){
        n = Math.abs(n)
        return (n - (Math.floor(n/2) * 2)) == 0
      }
      
      • dream_weasel
        link
        fedilink
        arrow-up
        4
        ·
        edit-2
        19 hours ago

        Minor simplification: this works even without taking absolute value first of you use fix instead of floor.

        Edit: I don’t know if fix is in the stock math library on second thought…

      • Kraiden@kbin.earth
        link
        fedilink
        arrow-up
        5
        ·
        22 hours ago

        Yep! I’m wrong. Pretty embarrassing!

        That’s a nice solution though! Gonna have to try and remember that one!