资讯专栏INFORMATION COLUMN

【5 kyu】Largest 5 digit number in a series

impig33 / 2440人阅读

摘要:原题目题目找出一个数值该数值将以字符串的形式传入中最大的五位数。如果数字的位数小于,则直接返回该数值如果数字的位数不小于六位,则依次截取连续的位数,求取最大值对比中使用了递归。

原题目

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
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中使用了递归。

但是递归每次调用都会在内存中开辟新的空间,若数据过大,很容易引起堆栈溢出。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/89338.html

相关文章

  • 【7 kyu】Descending Order

    摘要:若提供比较函数返回值返回值不变返回值交换位置升序排列后,再利用反序将字符串转换为可选参数,表示进制。规定使用,但是并不是所有的浏览器都遵循这个规定。因此,永远都要明确给出参数的值。若传入的字符串中含有非数字字符,将返回。 原题目 Your task is to make a function that can take any non-negative integer as a ar...

    ls0609 评论0 收藏0
  • 5 kyu】计算N的阶乘末尾几个0,Number of trailing zeros of N!

    摘要:函数可解析数字或者字符串,并返回其整数部分。其中为可选参数,默认为进制。字符串首字符为数字字符串首字符为非数字和在对负数进行取整时,结果是有差异的。 原题目 Write a program that will calculate the number of trailing zeros in a factorial of a given number. http://mathworld...

    beanlam 评论0 收藏0
  • [LeetCode/LintCode] Largest Palindrome Product

    Problem Find the largest palindrome made from the product of two n-digit numbers. Since the result could be very large, you should return the largest palindrome mod 1337. Example Input: 2Output: 987Ex...

    Barry_Ng 评论0 收藏0
  • 【7 kyu】Sum of two lowest positive integers

    摘要:原题目题目有一个不少于四个元素的数组,计算其中两个最小值的和。对比我写的方法比较常规,中采用了的解构赋值和箭头函数 原题目 Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 integers. No floats or empty ...

    fjcgreat 评论0 收藏0
  • 30s js代码片段 翻译

    摘要:可否被整除使用模运算符来检查余数是否等于。数值增加序号后缀使用模运算符来查找单位数和十位数的值。 这是对 github 上30s代码片段的翻译整理,由于作者的文档是通过脚本生成的,也就懒得去提pull了,整理了放到博客上供大家学习参考,后续会持续跟进翻译。 Array Array concatenation (合并参数) 使用 Array.concat() 来连接参数中的任何数组或值。...

    sevi_stuo 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<