DEV Community

Cover image for Can you hack this? #2
Alfredo Salzillo
Alfredo Salzillo

Posted on

Can you hack this? #2

Write an isEven function to check if a number is even without using the modulus operator.

const isEven = (n) => ...

isEven(2) // => true 
isEven('127') // => false
isEven('12abc2') // => false 
Enter fullscreen mode Exit fullscreen mode

Discussion (10)

Collapse
jonathanarnault profile image
Jonathan ARNAULT • Edited on

One liner solution :

const isEven = (n) => (+n && (n & 1)) === 0
Enter fullscreen mode Exit fullscreen mode
Collapse
pybash profile image
PyBash

Solved!

const isEven = (n) => {
  q = n/2
  ans = q===parseInt(q)
  if (ans==true) {
    return true
  }
  else {
    return false
  }
}

console.log(isEven(2)) // => true
console.log(isEven(127)) // => false
console.log(isEven('127')) // => false
console.log(isEven('12abc2')) // => false
Enter fullscreen mode Exit fullscreen mode
Collapse
ironcladdev profile image
IroncladDev

Instead of doing

if (ans==true) {
    return true
  }
  else {
    return false
  }
Enter fullscreen mode Exit fullscreen mode

Try

return ans == true;
Enter fullscreen mode Exit fullscreen mode
Collapse
omicron666 profile image
Omicron
isEven=n=>!!(+n+1<<31)
Enter fullscreen mode Exit fullscreen mode
Collapse
vicainelli profile image
Vinicius Cainelli • Edited on

Without convert to Number

const isEven = (n) => {
  const rgx = new RegExp('^\d*[02468]$')
  return rgx.test(n)
};
Enter fullscreen mode Exit fullscreen mode
Collapse
idodav profile image
Ido David

another solution:
isEven = (num) => Number.isInteger(num) && (!(num & 1))

Collapse
alfredosalzillo profile image
Alfredo Salzillo Author

Can anyone solve it without converting into a number?

Collapse
ironcladdev profile image
IroncladDev

I don't know if that's possible. I mean, using the parseInt function could work if someone inputs a string.

Collapse
alfredosalzillo profile image
Alfredo Salzillo Author

A Little help, you can use a regexp

Collapse
spino233 profile image
Angelo Caci

const isEven = (n) => !!n.toString().match("^[0-9]*[02468]$");