找规律

  • 从右边起每三个一组,三位数加 “hundred”,两位数两种情况,第二位是1和不是1,个位数直接转换
  • 第一组后开始,每组间按顺序加上['thousand','million','billion']。例如i=0即第一组后应加上['thousand','million','billion'][i%3] 也就是"thousand";i=1即第二组后应加上['thousand','million','billion'][i%3] 也就是 "million"......依次类推

以下为python代码实现

unit = ['thousand','million','billion']
num = {'1':'one', '2':'two', '3':'three', '4':'four', '5':'five', '6':'six', '7':'seven', '8':'eight', '9':'nine'}
teen = {'10':'ten','13':'thirteen','14':'fourteen', '15':'fifteen','16':'sixteen','17':'seventeen','18':'eighteen','19':'nighteen'}
ty = {'2':'twenty','3':'thirty','4':'forty', '5':'fifty', '6': 'sixty', '7':'seventy', '8':'eighty','9':'ninety'}
while 1:
    try:
        a = list(input()[::-1])
        # 从右边起每三个一组
        b = [a[i:i+3][::-1] for i in range(0,len(a),3)]
        c = []
        for v in b:
            temp = ''
            # 如果一组里是三位数
            if len(v)==3:
                if v[0]!='0':
                    temp += num[v[0]]+ ' hundred'
                    if v[1] != '0' or v[2] != '0':
                        temp += ' and '
                if v[1] != '0':
                    if v[1] == '1':
                        temp += teen[v[1] +v[2]]
                    else:
                        temp += ty[v[1]]
                        if v[2] != '0':
                            temp += ' ' + num[v[2]]
                else:
                    if v[2] !='0':
                        temp += num[v[2]]
            # 如果一组里是两位数
            elif len(v) == 2:
                if v[0] != '0':
                    if v[0] == '1':
                        temp += teen[v[0]+v[1]]
                    else:
                        temp += ty[v[0]]
                        if v[1] != '0':
                            temp += ' ' + num[v[1]]
            # 如果是一位数
            elif len(v) == 1:
                temp += num[v[0]]
            c.append(temp)
        temp1 = 0
        temp2 = 1
        # 从右边起第一组开始每组后依次加['thousand','million','billion']
        while temp2 < len(c):
            c.insert(temp2, unit[temp1%3])
            temp1+=1
            # 因为插入了一个元素,temp需要+2,下次循环才能正确的在下一组后插入['thousand','million','billion']
            temp2+=2
        print(' '.join(c[::-1]))
    except:
        break