重构这段基本代码,确定数字是十位、百位还是千位等等

refactor this basic code that determines if number is in tens, hundreds, thousands etc

本文关键字:十位 百位 千位 代码 段基本 数字 重构      更新时间:2023-09-26
 if (n<100) {
     x = 10;
 } else if (n<1000) {
     x = 100;
 } else if (n<10000) {
     x = 1000;
 } else if (n....

等。等。

对于这类问题是否有一个简洁、可扩展的方法?我的大脑决定停止工作了。

var x = Math.pow( 10, Math.floor( Math.log(n) / Math.log(10) ) );

这个可能更可取,因为它作为常量可用,所以不需要每次都计算:

var x = Math.pow( 10, Math.floor( Math.log(n) / Math.LN10 ) );

它基本上可以归结为对数四舍五入。


Edit:由于log/的组合往往会导致错误,因此将商四舍五入也可能是一个好主意(目前为Math.log(1000) / Math.LN10 === 2.9999999999999996)。

var x = Math.pow( 10, Math.floor( Math.round( Math.log(1000) / Math.LN10 * 1e10 ) / 1e10 ) );

这种四舍五入可能会导致新的错误,但对于'正常'输入,答案现在通常是正确的。

这是一个使用递归的解决方案:

function find_place( x, n ) {
    return x >= 10 ? find_place( x/10, ++n || 1  ) : Math.pow( 10, n || 0 );
}
find_place( 3 );    // 1
find_place( 33 );   // 10
find_place( 333 );  // 100

EDIT:固定使用x >= 10代替x > 10


这是一个不需要Math.pow()的版本

function find_place(x, n) {
    return x >= 10 ? find_place(x / 10, (n || 1) * 10) : n || 1;
}

或者在循环中有效地运行相同的代码,而不是递归函数,以加快一点速度。

var x = 12345,
    n = 1;   // n will hold the result
while (x >= 10) {
  x /= 10;
  n *= 10;
}

一种清理方法是使其成为自己的方法,并带有返回值。这样你就避免了所有的else if

...
if (n < 100) return 10;
if (n < 1000) return 100;
if (n < 10000) return 1000; 
...

这并不像使用pow()函数@pimvdb建议的那样好,但它是一种更通用的好方法,可以清理像本文所示的那种"else-iffy"感觉的代码。

你可以试试

x=Math.pow(10, Math.floor(Math.log(n)/Math.LN10));

我需要做一些类似的事情,并想到了以下:

x = Math.pow( 10, ( '' + n ).length - 1 );

和一些测试用例,jsFiddle:

n = 33;   // x = 10
n = 213;  // x = 100
n = 1776; // x = 1000

不知道性能是否比所有log的东西好,这里假设n是一个整数