受
Project Euler Problem 17 的启发,写了(其实是改写)一个能把数字转换成英语的Ruby 过程。
由于英语里面是千进制,故可以看成一个处理1, 000 以内的过程附加上单位(billion,million,thousand)。
# zero, one, two, three, four, five, six, seven, eight, nine, ten, # elevent, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, ... # thirty, forty, fifty, sixty, seventy, eighty, ninety # X hundred and X-X # one thousand $less_than_twenty = %w{zero one two three four five six seven eight nine ten elevent twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen} $tens = %w{"" "" twenty thirty forty fifty sixty seventy eighty ninety} def triple(n, unit) str = "" hundreds = n / 100 low_digit = n % 100 units_digit = n % 10 str += $less_than_twenty[hundreds] + " hundred and " if hundreds != 0 case low_digit when 0 str.chomp!(" and ") when 1 .. 19 str += $less_than_twenty[low_digit] when 20, 30, 40, 50, 60, 70, 80, 90 str += $tens[low_digit/10] else str += $tens[low_digit/10] + "-" + $less_than_twenty[units_digit] end str += unit end def num2str(n) str = "" if n / 1_000_000 > 0 str += triple(n / 1_000_000, " million ") end if (n % 1_000_000) / 1_000 > 0 str += triple((n % 1_000_000) / 1_000, " thousand ") end if n % 1_000 > 0 str += triple(n % 1_000, "") end str end p num2str(123_456_789)
由于英语里面是千进制,故可以看成一个处理1, 000 以内的过程附加上单位(billion,million,thousand)。