0

So I'm building various even-odd checkers. Standard method using python - x%2 == 0 as a boolean. Fine.

However, I've read that a different way of checking is to grab the binary string representing the number, then simply check the last digit of the string. If the last digit is 0, it's even, if it's 1, it's odd. For example:

00001011 = 11 Last digit is 1 11 is odd

00001110 = 14 Last digit is 0 14 is even.

It would amuse me to no end to be able to build even/odd checkers that use the binary string instead of a %2 check. The only thing I can't figure out, and my google-fu is failing me - how to grab and handle the string?

Threads for reference: Compare the last binary digit to 1 in MIPS assembly gives an assembly answer.

All of the other threads deal with getting the last digit of a normal number, IE last digit of 12345 is 5, and ignore the "How to read it in binary"

Selkie
  • 1,215
  • 1
  • 17
  • 34

1 Answers1

1

Try this:

def is_even(n):
    if "{0:b}".format(n).endswith(0): # Checks if converted number ends with 0
        return True
    else:
        return False
Maxim
  • 34
  • 5