Is & faster than % when checking for odd numbers?

前端 未结 8 942
鱼传尺愫
鱼传尺愫 2020-11-30 04:13

To check for odd and even integer, is the lowest bit checking more efficient than using the modulo?

>>> def isodd(num):
        return num & 1 a         


        
8条回答
  •  野性不改
    2020-11-30 04:31

    The best optimization you can get is to not put the test into a function. 'number % 2' and 'number & 1' are very common ways of checking odd/evenness, experienced programmers will recognize the pattern instantly, and you can always throw in a comment such as '# if number is odd, then blah blah blah' if you really need it to be obvious.

    # state whether number is odd or even
    if number & 1:
        print "Your number is odd"
    else:
        print "Your number is even"
    

提交回复
热议问题