首页 > 解决方案 > 如何获得可被scala中的除数整除的最接近的数字

问题描述

如何获得可被scala中的除数整除的最接近的数字。

例如

-if divisor -20 and dividend is 15, the number 15 has to be converted to 20
-if divisor -20 and dividend is 39, the number 39 has to be converted to 40 
-if divisor -20 and dividend is 45, the number 45 has to be converted to 60 
-if divisor -20 and dividend is 60, the number  conversion is not required.

我试过这个。但它不适用于负数。

def makeNum(num:Double,buc:Int){
if (num % buc == 0) println(num) else
println(  buc * (num/buc).ceil )
}
   makeNum(39,20) --> 40.0 - working
   makeNum(-10,20) --> -0.0 - Not correct

标签: scala

解决方案


你离得太近了。但是,问题并不是真正的负数,而是它总是搜索下一个数字,但壁橱可能是前一个数字。
此外,您的代码没有遵循关注点分离的常见最佳实践,您的函数应该只返回数字而不打印它。

这是完整的代码。

def findClosestDivisible(dividend: Int, divisor: Int): Int =
  if (dividend % divisor == 0) {
    // Return the dividend if it is already divisible.
    dividend
  } else {
    // Find the quotient.
    val quotient = dividend / divisor

    // 1st possible closest number. 
    val n1 = divisor * quotient

    // 2nd possible closest number.
    val n2 =
      if ((dividend * divisor) > 0)
        divisor * (quotient + 1)
      else
        divisor * (quotient - 1)

    // Return the closest number.
    import math.abs
    if (abs(dividend - n1) < abs(dividend - n2)) n1
    else n2
  }

注意:代码基于此页面上的算法,我只是限制自己在Scala中实现它。


推荐阅读