我想编写一个函数来查找给定乘数的数字的下一个倍数。源数和乘数都可以是 float 。
预期:
nextMult(3.654,0.5) = 4.0
nextMult(3.165,0.15) = 3.30
nextMult(3.452,0.002) = 3.452
nextMult(2, 0.3) = 2.1
nextMult(2, 0.2) = 2
nextMult(4, 3) = 6
我目前的解决方案:
public double nextMult(double source, double multiplier)
{
for (double i = (double)((long)source - multiplier); i <= source + multiplier;
i += multiplier)
{
if (i >= source)
return i;
}
}
我不喜欢多重类型转换。是否有更有效的方法或现有的图书馆解决方案可以做到这一点?
最佳答案
是的。由于您已经提供了一个有效的解决方案,您会注意到您已经提出了一个 O(n) 解决方案,该解决方案经过一定数量的操作并且在您找到它之前似乎递增。当您执行 nextMult(10000000000000, 1);
时,这会变得很可怕。我们会整天在这里手动迭代该循环。
然而,实际上有一个 O(1) 的解决方案。
int multiple = (int) (source / multiplier); //we get the whole number portion of the divided value, i.e. 4/3 = 1, 3.654/0.5 = 7
double remainder = source % multiplier; //we need to check for if it matches the higher
if(remainder > 0) {
multiple++; // and we want the next higher one
}
return multiplier * multiple;
也就是说,这只会处理正值。 我将把处理负值留给您作为练习。
编辑:您需要为模数实现 BigDoubles。 double 和模数显然互相讨厌。
关于java - 给定乘数的下一个数字倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26002304/