How to judge a int number odd or even? (the binary way)

心不动则不痛 提交于 2019-12-08 17:23:01

问题


I wanna use basic knowledge to improve the efficiency of code. I know that in binary system. when the last digit of number is 1,this is a odd number.and 0 is even number. How to use this way to judge a int number in python? Is that python give any build-in method to do it?


回答1:


AND it with 1:

  0000101001000101
  0000000000000001
&
__________________
  0000000000000001

If you get 1, the number is odd. If you get 0, the number is even. While this works, I would use the modulo operator instead:

>>> 8888 % 2
0
>>> 8881 % 2
1

It's faster and more straightforward to read:

In [5]: numbers = [random.randint(1, 1000000) for n in range(100000)]

In [6]: %timeit [n & 1 == 0 for n in numbers]
11 ms ± 390 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [7]: %timeit [n % 2 == 0 for n in numbers]
8.05 ms ± 244 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)



回答2:


You can & the number and 1, if you get 0 then the number is even, 1 means the number is odd.

>>> 2 & 1
0
>>> 3 & 1
1



回答3:


** PYTHON: LEAST SIGNIFICANT BIT METHOD**

>>> def is_odd(i): return bool(i & 1)

>>> def is_even(i): return not is_odd(i)

>>> [(j, is_odd(j)) for j in range(10)]
[(0, False), (1, True), (2, False), (3, True), (4, False), (5, True), (6, False), (7,     
True), (8, False), (9, True)]
>>> [(j, is_even(j)) for j in range(10)]
[(0, True), (1, False), (2, True), (3, False), (4, True), (5, False), (6, True), (7,   
False), (8, True), (9, False)]
>>> 

See If this can helps you or not.

Explanation:
Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.




回答4:


You can just use the & operator to check if the lowest bit is set;

a = 77
is_odd = bool(a & 1)
print is_odd              # Prints True

a = 64
is_odd = bool(a & 1)
print is_odd              # Prints False



回答5:


# Modular Congruencies #

>> def is_even(i):
    return (i % 2) == 0

>>> is_even(1)
False  
>>> is_even(2)
True
>>>


来源:https://stackoverflow.com/questions/16382403/how-to-judge-a-int-number-odd-or-even-the-binary-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!