vladislavkopilov

Largest 5 digit number in a series

Mar 15th, 2016
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.01 KB | None | 0 0
  1. =begin
  2. Largest 5 digit number in a series
  3.  
  4. link: http://www.codewars.com/kata/largest-5-digit-number-in-a-series/
  5.  
  6. description:
  7. In the following 6 digit number:
  8. 283910
  9. 91 is the greatest sequence of 2 digits.
  10. 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.
  11.  
  12. =end
  13.  
  14. #my version
  15. def solution(digits)
  16.   str = digits.to_s
  17.   maxsum_str = ""
  18.   for index in 0...str.length-4
  19.     sum = "#{str[index]}#{str[index+1]}#{str[index+2]}#{str[index+3]}#{str[index+4]}"
  20.     if( sum.to_i > maxsum_str.to_i )
  21.       maxsum_str = sum
  22.     end
  23.     if( sum.to_i==99999 )
  24.       return maxsum_str.to_i
  25.     end
  26.   end
  27.  
  28.   return maxsum_str.to_i
  29.  
  30. end
  31.  
  32. #best practices #1
  33. def solution(digits)
  34.   digits.split('').each_cons(5).max.join.to_i
  35. end
  36.  
  37. #best practices #2
  38. def solution(digits)
  39.   digits.scan(/\d{5}/).max.to_i
  40. end
Advertisement
Add Comment
Please, Sign In to add comment