In the following 6 digit number:283910
91 is the greatest sequence of 2 digits.javascript
In the following 10 digit number:1234567890
67890
is the greatest sequence of 5 digits.java
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.git
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; }
function solution(digits){ if (digits.length <= 5) return Number(digits); return Math.max(Number(digits.substr(0, 5)), solution(digits.substr(1))); }
Clever Solution中使用了递归。code
可是递归每次调用都会在内存中开辟新的空间,若数据过大,很容易引发堆栈溢出。递归