边工作边刷题:70天一遍leetcode: day 58
Integer to English Words
要点:类似roman to integer,三位一组计算,要点:
- 要从低位开始,因为不知道最高位实际是哪个位。类似的最高三位可能有短缺位,所以先reverse整个string以便3位一组loop的时候不会漏掉最高位(这个也是错误点)。
错误点:
- Ten也会表示出来,所以这位不是空
- 计算3位的逻辑不是全部if .. else,而是后两位if .. else .. 最高位是if
- 不要位数组中的字符留空格,而是利用list join时添加空格
- TypeError: can only join an iterable: " ".join(res.reverse()): 错误原因是res.reverse()是in-place function,返回的是None
test cases: 1234567, 20, 0, 1000, 100000
class Solution(object):
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
def computeThree(num):
one = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
# error 1: "Ten" instead of ""
ten = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
ten_2 = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
res = []
if num/100!=0:
res.append(one[num/100]+ " Hundred")
# error 3: not elif
if (num%100)/10==1:
res.append(ten[num%10])
else:
# error 2:
# error 5: 20 => "Twenty " vs "Twenty"
if num%100/10 >= 2:
res.append(ten_2[num%100/10])
if num%10>0:
res.append(one[num%10])
return " ".join(res)
if num==0: return "Zero"
base = ["", " Thousand", " Million", " Billion"]
str_num = str(num)[::-1]
# error 4: why reverse
divide_list = [str_num[i:i+3][::-1] for i in xrange(0, len(str_num), 3)]
# print divide_list
res = []
for i in xrange(len(divide_list)):
three = computeThree(int(divide_list[i]))
if three:
res.append(three + base[i])
res.reverse()
return " ".join(res)