Project Euler Problem 17

問題

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.

ソース

class Integer
  @@ns1 = [
    "zero", "one","two","three","four","five","six","seven","eight","nine", 
    "ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"]
  @@ns10 = ["", "", "twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"]
  @@ns100 = "hundred"
  @@ns1000 = "thousand"
  def to_s2
    str = []
    unless self < 20
      str.push("#{@@ns1[self / 1000]} #{@@ns1000}") if self >= 1000
      str.push("#{@@ns1[self / 100 % 10]} #{@@ns100}") unless (self / 100 % 10).zero?
      unless (self % 100).zero?
        if self % 100 < 20
          str.push(@@ns1[self % 100])
        elsif !(self % 100).zero?
          unless (self / 10 % 10).zero?
            if (self % 10).zero?
              str.push(@@ns10[self / 10 % 10])
            else
              str.push("#{@@ns10[self / 10 % 10]}-#{@@ns1[self % 10]}")
            end
          else
            str.push(@@ns1[self % 10])
          end
        end
      end
    else
      str.push(@@ns1[self]);
    end

    if str.size >= 2
      str[str.size] = str.last
      str[str.size - 2] = "and"
    end

    str.join(" ")
  end
end

puts (1..1000).inject(0) {|l, x| l + x.to_s2.scan(/[a-z]/).size}

解答

21124

感想

難しくはないが、見た目かなり面倒な問題だけど、以外に楽チンだった
このソースはいずれ何かに使えるカモ。。

あふぉな間違いwww

900 => nine hundred and zero