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 15:05

IsOdd(int x) { return true; }

Proof of correctness - consider the set of all positive integers and suppose there is a non-empty set of integers that are not odd. Because positive integers are well-ordered, there will be a smallest not odd number, which in itself is pretty odd, so clearly that number can't be in the set. Therefore this set cannot be non-empty. Repeat for negative integers except look for the greatest not odd number.

查看更多
心情的温度
3楼-- · 2019-01-02 15:07

+66% faster > !(i%2) / i%2 == 0

int isOdd(int n)
{
    return n & 1;
}

The code checks the last bit of the integer if it's 1 in Binary

Explanation

Binary  :   Decimal
-------------------
0000    =   0
0001    =   1
0010    =   2
0011    =   3
0100    =   4
0101    =   5
0110    =   6
0111    =   7
1000    =   8
1001    =   9
and so on...

Notice the rightmost bit is always 1 for Odd numbers.

the & bitwise AND operator checks the rightmost bit in our return line if it's 1

Think of it as true & false

When we compare n with 1 which means 0001 in binary (number of zeros doesn't matter).
then let's just Imagine that we have the integer n with a size of 1 byte.

It'd be represented by 8-bit / 8-binary digits.

If the int n was 7 and we compare it with 1, It's like

7 (1-byte int)|    0  0  0  0    0  1  1  1
       &
1 (1-byte int)|    0  0  0  0    0  0  0  1
********************************************
Result        |    F  F  F  F    F  F  F  T

Which F stands for false and T for true.

It compares only the rightmost bit if they're both true. So, automagically 7 & 1 is True.

What if I want to check the bit before the rightmost?

Simply change n & 1 to n & 2 which 2 represents 0010 in Binary and so on.

I suggest using hexadecimal notation if you're a beginner to bitwise operations
return n & 1; >> return n & 0x01;.

查看更多
余欢
4楼-- · 2019-01-02 15:08
// C#
bool isEven = ((i % 2) == 0);
查看更多
余欢
5楼-- · 2019-01-02 15:08

For the sake of discussion...

You only need to look at the last digit in any given number to see if it is even or odd. Signed, unsigned, positive, negative - they are all the same with regards to this. So this should work all round: -

void tellMeIfItIsAnOddNumberPlease(int iToTest){
  int iLastDigit;
  iLastDigit = iToTest - (iToTest / 10 * 10);
  if (iLastDigit % 2 == 0){
    printf("The number %d is even!\n", iToTest);
  } else {
    printf("The number %d is odd!\n", iToTest);
  }
}

The key here is in the third line of code, the division operator performs an integer division, so that result are missing the fraction part of the result. So for example 222 / 10 will give 22 as a result. Then multiply it again with 10 and you have 220. Subtract that from the original 222 and you end up with 2, which by magic is the same number as the last digit in the original number. ;-) The parenthesis are there to remind us of the order the calculation is done in. First do the division and the multiplication, then subtract the result from the original number. We could leave them out, since the priority is higher for division and multiplication than of subtraction, but this gives us "more readable" code.

We could make it all completely unreadable if we wanted to. It would make no difference whatsoever for a modern compiler: -

printf("%d%s\n",iToTest,0==(iToTest-iToTest/10*10)%2?" is even":" is odd");

But it would make the code way harder to maintain in the future. Just imagine that you would like to change the text for odd numbers to "is not even". Then someone else later on want to find out what changes you made and perform a svn diff or similar...

If you are not worried about portability but more about speed, you could have a look at the least significant bit. If that bit is set to 1 it is an odd number, if it is 0 it's an even number. On a little endian system, like Intel's x86 architecture it would be something like this: -

if (iToTest & 1) {
  // Even
} else {
  // Odd
}
查看更多
裙下三千臣
6楼-- · 2019-01-02 15:12

[Joke mode="on"]

public enum Evenness
{
  Unknown = 0,
  Even = 1,
  Odd = 2
}

public static Evenness AnalyzeEvenness(object o)
{

  if (o == null)
    return Evenness.Unknown;

  string foo = o.ToString();

  if (String.IsNullOrEmpty(foo))
    return Evenness.Unknown;

  char bar = foo[foo.Length - 1];

  switch (bar)
  {
     case '0':
     case '2':
     case '4':
     case '6':
     case '8':
       return Evenness.Even;
     case '1':
     case '3':
     case '5':
     case '7':
     case '9':
       return Evenness.Odd;
     default:
       return Evenness.Unknown;
  }
}

[Joke mode="off"]

EDIT: Added confusing values to the enum.

查看更多
春风洒进眼中
7楼-- · 2019-01-02 15:13

Portable:

i % 2 ? odd : even;

Unportable:

i & 1 ? odd : even;

i << (BITS_PER_INT - 1) ? odd : even;
查看更多
登录 后发表回答