给定一个数字,我怎样才能找到最接近的两个以1,2.5或5开头的数字? (10,25,50,100,250,500,1000 ......无穷无尽)
结果应该是最接近的最接近的数字,一个低于它。
例如:数字420应返回250和500。 例如:数字10应返回10和25。
如果它有用,可以使用Lodash。
感谢。
答案 0 :(得分:2)
好的,我想我会根据你的评论理解。
// Finds the two numbers on each side for any number.
function nearest(n) {
let m = multiplier(n);
return nearest10(n / m).map(n => n * m);
}
// Finds the two numbers on each side for numbers between 1 and 10.
function nearest10(n) {
return n < 2.5 ? [1, 2.5] : n < 5 ? [2.5, 5] : [5, 10];
}
// Returns the neareast power of 10 less than or equal to n.
function multiplier(n) {
return Math.pow(10, Math.floor(Math.log10(n)));
}
以下是结果示例:
console.log(nearest(2)); // [1, 2.5]
console.log(nearest(420)); // [250, 500]
console.log(nearest(79310)); // [50000, 100000]
答案 1 :(得分:1)
首先用科学记数法写出数字以摆脱规模。
420 = 4.2x10^2
然后在[1, 2.5)
,[2.5, 5)
,[5, 10)
中找到尾数。
4.2 in [2.5, 5)
转移指数,
2.5x10^2 = 250, 5x10^2 = 500
使用基数10对数
可以做得更好L= log(X) / log(10)
E= floor(L)
L= L - E
if L < log(2.5), LB= pow(10, N), UB= 2.5 * pow(10,N)
else if L < log(5) , LB= 2.5 * pow(10, N), UB= 5 * pow(10,N)
else LB= 5 * pow(10, N), UB= 10 * pow(10,N)
答案 2 :(得分:0)
function findPrevAndNext(x){
// returns the next highest value and previous
// lower value in the infinite series
// [1, 2.5, 5, 10, 25, 50, 100, ...]
var top = 5;
while(top < x){
top = top * 10;
}
var mid = top / 2; // ex: 5/2 = 2.5
var bot = top / 5; // ex: 5/5 = 1
var prev, next = 0;
if(x >= mid){
prev = mid;
next = top;
}
else if(x >= bot){
prev = bot;
next = mid;
}
else{
prev = bot / 2;
next = bot
}
return Array(prev,next);
}