Would you use num%2 or num&1 to check if a number is even?

后端 未结 12 2860
南旧
南旧 2020-12-18 19:19

Well, there are at least two low-level ways of determining whether a given number is even or not:

 1. if (num%2 == 0) { /* even */ } 
 2. if ((num&1) ==          


        
12条回答
  •  一个人的身影
    2020-12-18 19:41

    Any modern compiler will optimise away the modulo operation, so speed is not a concern.

    I'd say using modulo would make things easier to understand, but creating an is_even function that uses the x & 1 method gives you the best of both worlds.

提交回复
热议问题