【5 kyu】Largest 5 digit number in a series
文章目录
原题目
In the following 6 digit number:283910
91 is the greatest sequence of 2 digits.
In the following 10 digit number:123456789067890 is the greatest sequence of 5 digits.
Complete the solution so that it returns the largest five digit number found within the number given. The number will be passed in as a string of only digits. It should return a five digit integer. The number passed may be as large as 1000 digits.
题目:找出一个数值(该数值将以字符串的形式传入)中最大的五位数。
My Solution
- 如果数字的位数小于6,则直接返回该数值
- 如果数字的位数不小于六位,则依次截取连续的5位数,求取最大值
function solution(digits){
if(digits < 100000) return Number(digits);
var maxNum = digits.substr(0, 5);
for(var i=1, l=digits.length - 4; i<l; i++) {
maxNum = Math.max(maxNum, digits.substr(i, 5));
}
return maxNum;
}
Clever
function solution(digits){
if (digits.length <= 5) return Number(digits);
return Math.max(Number(digits.substr(0, 5)), solution(digits.substr(1)));
}
对比
Clever Solution中使用了递归。
但是递归每次调用都会在内存中开辟新的空间,若数据过大,很容易引起堆栈溢出。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论