将数字转换为ruby中的单词 - 改进我的递归解决方案

时间:2016-02-26 16:26:47

标签: ruby string recursion

问题在于您将数字转换为单词 - 300将转换为"三百"。我知道这个问题已经在堆栈溢出时解决了,但是我正在寻求关于我的特定递归解决方案的一些建议。

我的解决方案适用于除数字之外的所有数字: 100,1000,1000000

以上将返回"百","千","百万"。我理解为什么会这样。

300,3300,32000,35000等。任何数字%100或1000或1000000 == 0将返回为"三千三百零"

我唯一成功的想法是使用第二种方法get_words删除"零"如果数字大于0,则通过in_words运行数字之后的解决方案,然后返回"一个"如果数字是100/1000/1000000 ...

,则编号而不是in_words

由于这里使用递归的限制,我的解决方案可能只能像这样工作,但也许我错过了一些东西。任何人都可以提供一种方法来调整我的解决方案来解决这个问题吗?

NUMBER_DICTIONARY = {
  0 => "zero",
  1 => "one",
  2 => "two",
  3 => "three",
  4 => "four",
  5 => "five",
  6 => "six",
  7 => "seven",
  8 => "eight",
  9 => "nine",
  10 => "ten",
  11 => "eleven",
  12 => "twelve",
  13 => "thirteen",
  14 => "fourteen",
  15 => "fifteen",
  16 => "sixteen",
  17 => "seventeen",
  18 => "eighteen",
  19 => "nineteen",
  20 => "twenty",
  30 => "thirty",
  40 => "forty",
  50 => "fifty",
  60 => "sixty",
  70 => "seventy",
  80 => "eighty",
  90 => "ninety",
  100 => "hundred",
  1000 => "thousand",
  1000000 => "million"
  }

def get_words(number)
  result = in_words(number)
  return  "one" + " " + NUMBER_DICTIONARY[number] if (number == 100 || number == 1000 || number == 1000000)
  return result.split(" ").delete_if { |word| word == "zero"}.join(" ") if result.include?("zero") && number > 0 
  result
end

def in_words(number)
  #base case
  return NUMBER_DICTIONARY[number] if NUMBER_DICTIONARY.include?(number)
  #recursion
  return in_words(number / 1000000) + " " + in_words(1000000) + " " + in_words(number % 1000000) if number > 1000000
  return in_words(number / 1000) + " " + in_words(1000) + " " + in_words(number % 1000) if number > 1000
  return in_words(number / 100) + " " + in_words(100) + " " + in_words(number % 100) if number > 100
  return in_words((number / 10) * 10) + " " + in_words(number % 10) if number > 20 

end

0 个答案:

没有答案