javascript - 旋转数组并返回最大数,不适用于非常大的数

标签 javascript algorithm

我正在尝试解决算法挑战。以下是说明:

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/

相关文章:

algorithm - 模拟理论 - 如何排序只有 log(p)?

algorithm - 查找多边形内的任意点

java - 扩展欧氏算法 JAVA RSA

javascript - 如何在 react-leaflet 中使用带有动态标记的边界

javascript - 使用 javascript/jquery (Google Chrome) 隐藏元素后无法显示元素

javascript - 将脚本加载到 TypeScript 文件中?

string - 如何用更少的内存保存多个相似(分层格式)的字符串?

javascript - ReactJS:预期 onClick 监听器是一个函数,而不是类型字符串

javascript - 无法使用 Greasemonkey 单击此超链接

java - 关于基数排序的 Java 实现的解释