原题目
In the following 6 digit number:283910
91 is the greatest sequence of 2 digits.
In the following 10 digit number:1234567890
67890
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中使用了递归。
但是递归每次调用都会在内存中开辟新的空间,若数据过大,很容易引起堆栈溢出。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。