美文网首页
和果子一起来做题-Project Euler-17-R语言版本

和果子一起来做题-Project Euler-17-R语言版本

作者: 9d760c7ce737 | 来源:发表于2018-01-28 18:23 被阅读21次
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.

把数字转换成字母并计算字符数,比如1就是one,3个字母,342就是three hundred and forty-two就是23个字母,不计算空格和小横线。
现在问1到1000一共有多少字母?

构造能够转换数字到字母的函数

numbers2words <- function(x){
  ##读2位数
  read2digits <- function(x){
    x <- as.numeric(x)
    if(x <=19){
      return(teens[x-9])
    }else{
      x <- as.character(x)
      str <- unlist(strsplit(x,''))
      return(paste(tens[as.numeric(str[1])-1],ones[as.numeric(str[2])+1],collapse = " "))
    }
  }
  ##读3位数
  read3digits <- function(x){
    x <- as.character(x)
    str <- unlist(strsplit(x,''))
    #last two number
    if (as.numeric(str[2])==0 & as.numeric(str[3])!=0){
      return(paste(ones[as.numeric(str[1])+1],"hundred and",ones[as.numeric(str[3])+1],collapse = " "))
    }else if(as.numeric(str[2])==0 & as.numeric(str[3])==0){
      return(paste(ones[as.numeric(str[1])+1],"hundred",collapse = " "))
    }else{
      lasttwo <- as.numeric(paste0(str[2],str[3]))
      return(paste(ones[as.numeric(str[1])+1],"hundred and",read2digits(lasttwo)))
    }
  }
  ones <- c("","one", "two", "three", "four", "five", "six", "seven",
            "eight", "nine") 
  teens <- c("ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
            "sixteen", " seventeen", "eighteen", "nineteen")
  tens <- c("twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty",
            "ninety") 
  #first we want to know the digits of the number
  x <- as.character(x)
  
  digits <- nchar(x)
  if (digits ==1){
    x <- as.numeric(x)
    return(ones[x+1])
  }else if(digits ==2){
    return(read2digits(x))
  }else if(digits ==3){
    return(read3digits(x))
  }else if(x=="1000"){
    return("one thousand")
  }else{
    return("number should be less than 1000")
  }
}

测序函数

> numbers2words(23)
[1] "twenty three"
> numbers2words(100)
[1] "one hundred"
> numbers2words(965)
[1] "nine hundred and sixty five"

这个函数只能转换1000以内的数字

> numbers2words(1001)
[1] "number should be less than 1000"

构造能够计算字母的函数

numberofletter <- function(x){
  return(sum(nchar(unlist(strsplit(numbers2words(x),' ')))))
}

测试

> numberofletter(1)
[1] 3
> numberofletter(342)
[1] 23
> numberofletter(115)
[1] 20

计算总和

> sum(sapply(1:1000, numberofletter))
[1] 21124

相关文章

网友评论

      本文标题:和果子一起来做题-Project Euler-17-R语言版本

      本文链接:https://www.haomeiwen.com/subject/gxezaxtx.html