Codewars 7 Kyu : Round to the next multiple of 5

题目

Given an integer as input, can you round it to the next (meaning, “higher”) 5?

Examples:

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.

代码

public class Kata
{
  public static int RoundToNext5(int n)
  {
    int num=n/5;
    int re=n%5;
    if(re==0) return n;
    if(n==0) {return 0;}   
    else if(n<0){return num*5;}
    else {return (num+1)*5;}
    }
  }

解题思路

本题解题关键在于给的几个例子,从中可以得出以下条件:
1.当n被5除尽时,返回它本身
2.当n=0,时返回0
3.当n>0时和小于0时又有两种情况

发表评论

您的电子邮箱地址不会被公开。