Test if a number is within 2 of a multiple of 10 I have solved this exercise, but it looks really redundant. Is there a built-in function in Java or a cleaner way to caluclate mod of a value + deviation without multiple OR statements? If I had to calculate this for a deviation of 5, this would then require a lot of repetition.


  Given a non-negative number "num", return true if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2.



    public boolean nearTen(int num) {
        return isMod10(num) || isMod10(num - 1) || isMod10(num + 1) || isMod10(num - 2) || isMod10(num + 2);
    }

    private boolean isMod10(int num) {
        return num % 10 == 0;
    }
You should read about congruent integers and modular arithmic. The distance of a number to a base is the minimum distance of its congruent value and its inverted congruent value.

 public boolean nearBase(int num, int base, int deviation) {

        // ..TODO check guards, normalize input or throw exceptions 
        // - base and deviation are expected strict positive integers
        // - deviation is expected smaller than base
        // - num is expected a positive integer

        var congruent = num % base;
        var inverted = base - congruent;
        var distance = Math.min(congruent, inverted);
        return distance &lt;= deviation;
    }

 // your method rewritten -&gt;
 public boolean nearTen(int num) {
        return nearBase(num, 10, 2);
    }