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

后端 未结 12 2857
南旧
南旧 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:38

    Both approaches are not obvious especially to someone who is new to programming. You should define an inline function with a descriptive name. The approach you use in it won't matter (micro optimizations most likely won't make your program faster in a noticeable way).

    Anyway, I believe 2) is much faster as it doesn't require a division.

提交回复
热议问题