Simplest way to calculate amount of even numbers in given range

前端 未结 16 2410
小蘑菇
小蘑菇 2021-02-13 14:10

What is the simplest way to calculate the amount of even numbers in a range of unsigned integers?

An example: if range is [0...4] then the answer is 3 (0,2,4)

I\

16条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-13 14:39

    Hint 1: The modulo operator will return the remainder of the current number
    Hint 2: You don't need a for loop
    Hint 3: A range is continuous
    Hint 4: The number of even numbers in a continuous range are half even (sometimes half + 1, sometimes half - 1)
    Hint 5: Building on Hint1: Consider also what (being + end + 1) % 2 gives
    Hint 6: Most or all of the answers in this thread are wrong
    Hint 7: Make sure you try your solution with negative number ranges
    Hint 8: Make sure you try your solution with ranges spanning both negative and positive numbers

提交回复
热议问题