How do I check if an integer is even or odd? [clos

2019-01-02 14:24发布

How can I check if a given number is even or odd in C?

标签: c integer
30条回答
余欢
2楼-- · 2019-01-02 14:51

In the "creative but confusing category" I offer:

int isOdd(int n) { return n ^ n * n ? isOdd(n * n) : n; }

A variant on this theme that is specific to Microsoft C++:

__declspec(naked) bool __fastcall isOdd(const int x)
{
    __asm
    {
        mov eax,ecx
        mul eax
        mul eax
        mul eax
        mul eax
        mul eax
        mul eax
        ret
    }
}
查看更多
孤独寂梦人
3楼-- · 2019-01-02 14:53

If you want to be efficient, use bitwise operators (x & 1), but if you want to be readable use modulo 2 (x % 2)

查看更多
荒废的爱情
4楼-- · 2019-01-02 14:54

I know this is just syntactic sugar and only applicable in .net but what about extension method...

public static class RudiGroblerExtensions
{
    public static bool IsOdd(this int i)
    {
        return ((i % 2) != 0);
    }
}

Now you can do the following

int i = 5;
if (i.IsOdd())
{
    // Do something...
}
查看更多
素衣白纱
5楼-- · 2019-01-02 14:55

Here is an answer in Java:

public static boolean isEven (Integer Number) {
    Pattern number = Pattern.compile("^.*?(?:[02]|8|(?:6|4))$");
    String num = Number.toString(Number);
    Boolean numbr = new Boolean(number.matcher(num).matches());
    return numbr.booleanValue();
}
查看更多
怪性笑人.
6楼-- · 2019-01-02 14:57

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:

  • 2's complement
  • 1's complement
  • sign and magnitude

Checking like this:

isEven = (x & 1);

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:

isEven = (x & 1) ^ ((-1 & 1) | ((x < 0) ? 0 : 1)));

Thanks to ffpf for pointing out that the text box was eating everything after my less than character!

查看更多
不再属于我。
7楼-- · 2019-01-02 14:57

A nice one is:

/*forward declaration, C compiles in one pass*/
bool isOdd(unsigned int n);

bool isEven(unsigned int n)
{
  if (n == 0) 
    return true ;  // I know 0 is even
  else
    return isOdd(n-1) ; // n is even if n-1 is odd
}

bool isOdd(unsigned int n)
{
  if (n == 0)
    return false ;
  else
    return isEven(n-1) ; // n is odd if n-1 is even
}

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 !

查看更多
登录 后发表回答