我正在尝试解决算法挑战。以下是说明:
Take a number: 56789. Rotate left, you get 67895.
Keep the first digit in place and rotate left the other digits: 68957.
Keep the first two digits in place and rotate the other ones: 68579.
Keep the first three digits and rotate left the rest: 68597. Now it is over since keeping the first four it remains only one digit which rotated is itself.
You have the following sequence of numbers:
56789 -> 67895 -> 68957 -> 68579 -> 68597
and you must return the greatest: 68957.
Calling this function max_rot (or maxRot or ... depending on the language)
max_rot(56789) should return 68957
这是我的解决方案,它适用于所有测试,但是当给定更大的数字时,它会失败。有人可以告诉我为什么它失败了吗?它应该适用于所有情况。
function maxRot(n) {
var numbersArray =[];
n = n.toString().split("")
for(i=0;i<n.length;i++){
var extractedChars = n.splice(i,1)
n.push(extractedChars[0])
numbersArray.push(parseInt(n.join("")))
}
return Math.max(...numbersArray)
}
这里是一些错误的例子:
预期:507992495,实际得到:99249557
预期:433039515,实际得到:330395154
预期:210882952,实际得到:188295220
我哪里错了?
最佳答案
编辑:为清楚起见,在此处添加正确的解决方案(从我下面的评论中复制): 我发现你的逻辑有什么错误,你忘记添加序列的第一个数字 :) 将此行推到 for 循环内其他两行的上方:numbersArray.push(parseInt(n.join("")) ).此外,您也应该在离开 for 循环后添加最后一个字符串
关于javascript - 旋转数组并返回最大数,不适用于非常大的数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39760406/