Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ProjectEuler
- /**
- * Created by Mahesh Nema on 19-01-2017.
- */
- // Problem 17 Number letter counts
- /*
- If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
- If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
- NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen)
- contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.
- */
- object Euler17 extends App {
- val ones = List("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine")
- val tens = List("", "ten", "twenty", "thirt", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
- val eleveToNineteen = List("Eleven", "Twelve", "Thirteen", "Fourteen", "Fiveteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
- def twoDigit(num: Int) = {
- if (num / 10 == 0)
- ones(num)
- else if (num > 10 && num < 20)
- eleveToNineteen(num % 11)
- else {
- val tensPlace = num / 10
- val onesPalce = num % 10
- s"${tens(tensPlace)} ${ones(onesPalce)}"
- }
- }
- def threeDigit(num: Int) = {
- if (num / 100 == 0) {
- twoDigit(num)
- } else {
- val twoDigits = twoDigit(num % 100)
- s"${ones(num / 100)} hundred" + " " + {
- if (twoDigits.nonEmpty) {
- "and"
- } else {
- ""
- }
- } + twoDigits
- }
- }
- def number(num:Int) ={
- if (num / 1000 == 0) {
- threeDigit(num)
- } else {
- "One thousand"
- }
- }
- println((1 to 1000).map(number(_).filter(_ != ' ').length).sum)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement