如何判断一个INT数奇数还是偶数? (二进制方式) [英] How to judge a int number odd or even? (the binary way)

查看:254
本文介绍了如何判断一个INT数奇数还是偶数? (二进制方式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用的基本知识,以提高code的效率。
我知道,在双星系统。当编号的最后一位数字是1,这是一个奇number.and 0是偶数。
如何用这种方式来判断在python INT多少?就是,Python提供任何内置的方法来做到这一点?

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:

  0000101001000101
  0000000000000001
&
__________________
  0000000000000001

如果你得到 1 ,数量为奇数。如果你得到 0 ,这个数字是偶数。虽然这个作品,我会使用模运算符来代替:

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 works the same way, is just as fast and looks nicer:

In [65]: %timeit random.randint(1, 1000000) & 1 == 0
1000000 loops, best of 3: 1.02 us per loop

In [66]: %timeit random.randint(1, 1000000) % 2 == 0
1000000 loops, best of 3: 1.03 us per loop

这篇关于如何判断一个INT数奇数还是偶数? (二进制方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆