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

后端 未结 13 1468
Happy的楠姐
Happy的楠姐 2021-01-31 07:01

I have a few loops that I need in my program. I can write out the pseudo code, but I\'m not entirely sure how to write them logically.

I need -

if (num is          


        
13条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-31 07:17

    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. :-)

提交回复
热议问题