Even/Odd Number

Discussion in 'iOS Development' started by NolesFans, Aug 28, 2009.

  1. NolesFans

    NolesFans New Member

    Joined:
    Sep 23, 2008
    Messages:
    404
    Likes Received:
    0
    Device:
    iPod touch
    I was doing

    [OBJC]if (indexPath.row & 1) {
    // Odd Number
    } else {
    // Even Number
    }[/OBJC]

    Was this is only way?

    I was planing to do odd number as whiteColor and even number as a light color. Is there is a better way?
  2. SkylarEC

    SkylarEC Super Moderator Emeritus Staff Member

    Joined:
    Sep 19, 2007
    Messages:
    6,642
    Likes Received:
    129
    [OBJC]if (variable % 2 == 0) {
    //number is even
    } else {
    //number is odd
    }[/OBJC]

    The modulus operator returns the remainder after division. So, take a variable and divide it by two. If the remainder is zero, then the number us even. Else, if there is a remainder of one, the number is odd.
  3. Steaps

    Steaps New Member

    Joined:
    Oct 24, 2007
    Messages:
    5,074
    Likes Received:
    41
    Device:
    iPod touch
    I use the way Skylar posted, but question, whats the & do?
  4. Pelaez-1

    Pelaez-1 New Member

    Joined:
    May 5, 2008
    Messages:
    822
    Likes Received:
    0
    Device:
    iPhone
    It's an and operator at bit level.

    So if the number has the last bit as a 1, it will return true.

    For example (integers don't have only 4 bits, it's only an example)

    1000 = 8
    0001 = 1

    If you do an and with that, you'll get all 0s, which is 0, so the number is even.

    0101 = 5
    0001 = 1

    What and will return 0001 which is 1.
  5. Cyanidepoison

    Cyanidepoison Active Member

    Joined:
    Jan 18, 2008
    Messages:
    1,076
    Likes Received:
    2
    Using the bitwise-and operation is faster, but in your case comparing cell indexes, the tiny speed difference isn't going to help.

    It is barely noticeable over 100,000,000 iterations.

Share This Page