The challenge
Given an integer as input, can you round it to the next (meaning, “higher”) multiple of 5?
Examples:
1
2
3
4
5
6
7
8
9
10
|
input: output:
0 -> 0
2 -> 5
3 -> 5
12 -> 15
21 -> 25
30 -> 30
-2 -> 0
-5 -> -5
etc.
|
Input may be any positive or negative integer (including 0).
You can assume that all inputs are valid integers.
The solution in Python code
Option 1:
1
2
|
def round_to_next5(n):
return n + (5 - n) % 5
|
Option 2:
1
2
3
4
|
def round_to_next5(n):
while n%5!=0:
n+=1
return n
|
Option 3:
1
2
3
|
import math
def round_to_next5(n):
return math.ceil(n/5.0) * 5
|
Test cases to validate our solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
inp = 0
out = round_to_next5(inp)
test.assert_equals(out, 0, "Input: {}".format(inp))
inp = 1
out = round_to_next5(inp)
test.assert_equals(out, 5, "Input: {}".format(inp))
inp = -1
out = round_to_next5(inp)
test.assert_equals(out, 0, "Input: {}".format(inp))
inp = 5
out = round_to_next5(inp)
test.assert_equals(out, 5, "Input: {}".format(inp))
inp = 7
out = round_to_next5(inp)
test.assert_equals(out, 10, "Input: {}".format(inp))
inp = 20
out = round_to_next5(inp)
test.assert_equals(out, 20, "Input: {}".format(inp))
inp = 39
out = round_to_next5(inp)
test.assert_equals(out, 40, "Input: {}".format(inp))
|