最大旋转 - JavaScript
Rotate For a Max - JavaScript
正在尝试解决此问题 Codewars challenge。
给定一个数字,我们跟踪不同的(左)旋转结果并return获得最大的结果。
但是,这种旋转与典型的旋转不同 - 因为 n
位数在旋转后将保持不变,并且 n
随着每次旋转而增加。
例如,给定数字 56789
,我们将有:
67895
(6 stays in place, 7 gets rotated to the back)
68957
(6 and 8 stay in place, 9 gets rotated to the back)
68579
(6, 8, and 5 stay in place, 7 gets rotated to the back)
68597
(6, 8, 5, and 9 stay in place - no more rotations can occur)
然后 return 这些值的最大值 - 68957
.
我有以下代码:
function maxRot(n) {
let listOfNums = [];
let array = Array.from(n.toString());
let num = 0;
while (num < array.length -1) {
let number = array.splice(num, 1);
array.push(Number(number));
listOfNums.push(Number(array.join("")));
num++;
}
listOfNums.sort((a, b) => b - a);
return listOfNums[0];
}
console.log(maxRot(56789));
但是它在 Codewars 上接近一半的测试都失败了。
而且如你所见,我的逻辑是每次拼接一个数字,追加到数组的末尾,然后将更新后的数组压入一个listOfNums
数组,然后对那个数组进行排序从最大到最小和 return 第一个值。
不确定还可以尝试什么。
正如@georg 所指出的,我忘记将原始号码添加回列表中。
function maxRot(n) {
let listOfNums = [];
let array = Array.from(n.toString());
let num = 0;
while (num < array.length -1) {
let number = array.splice(num, 1);
array.push(Number(number));
listOfNums.push(Number(array.join("")));
num++;
}
listOfNums.unshift(n);
listOfNums.sort((a, b) => b - a);
return listOfNums[0];
}
正在尝试解决此问题 Codewars challenge。
给定一个数字,我们跟踪不同的(左)旋转结果并return获得最大的结果。
但是,这种旋转与典型的旋转不同 - 因为 n
位数在旋转后将保持不变,并且 n
随着每次旋转而增加。
例如,给定数字 56789
,我们将有:
67895
(6 stays in place, 7 gets rotated to the back)
68957
(6 and 8 stay in place, 9 gets rotated to the back)
68579
(6, 8, and 5 stay in place, 7 gets rotated to the back)
68597
(6, 8, 5, and 9 stay in place - no more rotations can occur)
然后 return 这些值的最大值 - 68957
.
我有以下代码:
function maxRot(n) {
let listOfNums = [];
let array = Array.from(n.toString());
let num = 0;
while (num < array.length -1) {
let number = array.splice(num, 1);
array.push(Number(number));
listOfNums.push(Number(array.join("")));
num++;
}
listOfNums.sort((a, b) => b - a);
return listOfNums[0];
}
console.log(maxRot(56789));
但是它在 Codewars 上接近一半的测试都失败了。
而且如你所见,我的逻辑是每次拼接一个数字,追加到数组的末尾,然后将更新后的数组压入一个listOfNums
数组,然后对那个数组进行排序从最大到最小和 return 第一个值。
不确定还可以尝试什么。
正如@georg 所指出的,我忘记将原始号码添加回列表中。
function maxRot(n) {
let listOfNums = [];
let array = Array.from(n.toString());
let num = 0;
while (num < array.length -1) {
let number = array.splice(num, 1);
array.push(Number(number));
listOfNums.push(Number(array.join("")));
num++;
}
listOfNums.unshift(n);
listOfNums.sort((a, b) => b - a);
return listOfNums[0];
}