在JavaScript中不使用字符串方法且不使用数组对整数进行排序
我们需要编写一个带数字的JavaScript函数。该函数应返回可重新排列数字位数的最小数字。
例如-
如果输入号码是-
const num = 614532;
那么输出应该是-
const output = 123456;
唯一的条件是我们不能使用任何String方法或任何数组来存储数据。
示例
为此的代码将是-
const num = 614532;
const sortDigits = num => {
const getDigit = e => Math.floor(num / 10 ** e) % 10;
const l = Math.ceil(Math.log10(num)) − 1;
let e = l;
while (e−−) {
const left = getDigit(e + 1);
const right = getDigit(e);
if (left <= right){
continue;
};
num += (right − left) * 9 * 10 ** e;
e = l;
};
return num;
}
console.log(sortDigits(num));输出结果
控制台中的输出将是-
123456