我有一个计算数字中最大数字的函数:
function maxDigit(n){
if(n == 0){
return 0;
}
else{
return Math.max(n%10, maxDigit(n/10));
}
}
console.log(maxDigit(16984));
返回值为9.840000000000003
如何修改此代码以便仅返回值 9 ?
最佳答案
Javascript 中没有整数 div,这就是使用“/”时的含义。
因此,要么使用 Math.floor,要么减去余数:
function maxDigit(n){
if(n == 0){ return 0;}
else{
var remainder = n % 10
return Math.max(remainder, maxDigit((n-remainder)*1e-1));
}
}
console.log(maxDigit(16984));
// output is 9
(迭代版本很容易推断出来:
function maxDigit(n){
n= 0 | n ;
var max=-1, remainder=-1;
do {
remainder = n % 10;
max = (max > remainder ) ? max : remainder ;
n=(n-remainder)*1e-1;
} while (n!=0);
return max;
}
console.log(maxDigit(16984));
// output is 9
console.log(maxDigit(00574865433));
// output is 8
)
关于javascript - 如何显示数字中最大的数字 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18761363/