我们需要编写一个带数字的JavaScript函数。该函数应返回最接近输入数字的10的幂。
例如-
f(1) = 1 f(5) = 1 f(15) = 10 f(43) = 10 f(456) = 100 f(999) = 100
const num = 2355; const num1 = 346; const num2 = 678; const nearestPowerOfTen = (num) => { let count = 0; while(num > 1){ count ++; num/= 10; }; return Math.pow(10, count-1) * (Math.round(num) ? 10: 1); } console.log(nearestPowerOfTen(num)); console.log(nearestPowerOfTen(num1)); console.log(nearestPowerOfTen(num2));
输出结果
控制台中的输出将是-
1000 100 1000