Testing if a list of integer is odd or even

后端 未结 5 519
借酒劲吻你
借酒劲吻你 2020-12-29 20:13

Trying to determine if my list of integer is made of odd or even numbers, my desired output is a list of true an/or false. Can I perform the following operation on the list

5条回答
  •  情书的邮戳
    2020-12-29 21:07

    There's at least 7 different ways to test if a number is odd or even. But, if you read through these benchmarks, you'll find that as TGH mentioned above, the modulus operation is the fastest:

    if (x % 2 == 0)
                   //even number
            else
                   //odd number
    

    Here are a few other methods (from the website) :

    //bitwise operation
    if ((x & 1) == 0)
           //even number
    else
          //odd number
    
    //bit shifting
    if (((x >> 1) << 1) == x)
           //even number
    else
           //odd number
    
    //using native library
    System.Math.DivRem((long)x, (long)2, out outvalue);
    if ( outvalue == 0)
           //even number
    else
           //odd number
    

提交回复
热议问题