Determining if a number is either a multiple of ten or within a particular set of ranges

For the first one, to check if a number is a multiple of use:

if (num % 10 == 0) // It's divisible by 10

For the second one:

if(((num - 1) / 10) % 2 == 1 && num <= 100)

But that's rather dense, and you might be better off just listing the options explicitly.


Now that you've given a better idea of what you are doing, I'd write the second one as:

   int getRow(int num) {
      return (num - 1) / 10;
   }

   if (getRow(num) % 2 == 0) {
   }

It's the same logic, but by using the function we get a clearer idea of what it means.


if (num is a multiple of 10) { do this }

if (num % 10 == 0) {
  // Do something
}

if (num is within 11-20, 31-40, 51-60, 71-80, 91-100) { do this }

The trick here is to look for some sort of commonality among the ranges. Of course, you can always use the "brute force" method:

if ((num > 10 && num <= 20) ||
    (num > 30 && num <= 40) ||
    (num > 50 && num <= 60) ||
    (num > 70 && num <= 80) ||
    (num > 90 && num <= 100)) {
  // Do something
}

But you might notice that, if you subtract 1 from num, you'll have the ranges:

10-19, 30-39, 50-59, 70-79, 90-99

In other words, all two-digit numbers whose first digit is odd. Next, you need to come up with a formula that expresses this. You can get the first digit by dividing by 10, and you can test that it's odd by checking for a remainder of 1 when you divide by 2. Putting that all together:

if ((num > 0) && (num <= 100) && (((num - 1) / 10) % 2 == 1)) {
  // Do something
}

Given the trade-off between longer but maintainable code and shorter "clever" code, I'd pick longer and clearer every time. At the very least, if you try to be clever, please, please include a comment that explains exactly what you're trying to accomplish.

It helps to assume the next developer to work on the code is armed and knows where you live. :-)


If you are using GCC or any compiler that supports case ranges you can do this, but your code will not be portable.

switch(num)
{
case 11 ... 20:
case 31 ... 40:
case 51 ... 60:
case 71 ... 80:
case 91 ... 100:
    // Do something
    break;
default:
    // Do something else
    break;
}