How can I check if a given number is even or odd in C?
相关问题
- Multiple sockets for clients to connect to
- Do the Java Integer and Double objects have unnece
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
In the "creative but confusing category" I offer:
A variant on this theme that is specific to Microsoft C++:
If you want to be efficient, use bitwise operators (
x & 1
), but if you want to be readable use modulo 2 (x % 2
)I know this is just syntactic sugar and only applicable in .net but what about extension method...
Now you can do the following
Here is an answer in Java:
In response to ffpf - I had exactly the same argument with a colleague years ago, and the answer is no, it doesn't work with negative numbers.
The C standard stipulates that negative numbers can be represented in 3 ways:
Checking like this:
will work for 2's complement and sign and magnitude representation, but not for 1's complement.
However, I believe that the following will work for all cases:
Thanks to ffpf for pointing out that the text box was eating everything after my less than character!
A nice one is:
Note that this method use tail recursion involving two functions. It can be implemented efficiently (turned into a while/until kind of loop) if your compiler supports tail recursion like a Scheme compiler. In this case the stack should not overflow !