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

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

    They're both pretty intuitive.

    I'd give a slight edge to num % 2 == 0, but I really don't have a preference. Certainly as far as performance goes, it's probably a micro-optimization, so I wouldn't worry about it.

提交回复
热议问题