HJ42 题解 | #学英语#

学英语

https://www.nowcoder.com/practice/1364723563ab43c99f3d38b5abef83bc

#思路:
#把需要用到的词汇存起来
#定义一个函数f处理1-1000的,函数中需要处理各种特殊情况
#使用函数f,分别处理1000以内级、1000级、百万级

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

s=input()
s1=int(s)
ans=""
#对于1-1000的定义一个函数,因为后面大量使用
def f(s):
    #如果在b中直接返回s,这样解决整十还要计算个位的问题
    if s in b:
        if int(s)<100:
            res=a[b.index(s)]
        else:
            res="one "+a[b.index(s)]
        return res
    ge=s[-1]
    if int(s)<10:
        if ge=="0":
            res=""
        else:
            res=a[b.index(ge)]
    elif int(s)<100:#小于100
        shi=s[-2]+"0"
        if ge=="0":
            res=a[b.index(shi)]
        else:
            res=a[b.index(shi)]+" "+a[b.index(ge)]#拼接结果

    else:#大于100,小于1000
        shi=s[-2]+"0"
        bai=s[-3]
        if s[-2:] in b:#类似919这种,后两位是直接存在的
            res=a[b.index(bai)]+" hundred and "+a[b.index(s[-2:])]
            return res
        if ge=="0":#类似400或430这样的
            if shi=="00":#特殊情况,403这样的,十位为0
                res=a[b.index(bai)]+" hundred"
            else:
                res=a[b.index(bai)]+" hundred and "+a[b.index(shi)]
        else:
            if shi=="00":#特殊情况,403这样的,十位为0
                res=a[b.index(bai)]+" hundred and "+a[b.index(ge)]
            else:
                res=a[b.index(bai)]+" hundred and "+a[b.index(shi)]+" "+a[b.index(ge)]
    return res

#按规则实现
#小于1000
if s1<1000:
    ans=f(s)
#大于1000,小于百万
elif s1<1000000:
    ans=f(s[:-3])+" thousand "+f(s[-3:])
#大于百万
else:
    ans=f(s[:-6])+" million "+f(s[-6:-3])+" thousand "+f(s[-3:])

print(ans)

#华为##华为od##华为机试##华为od机试#
华为HJ103所有解法 文章被收录于专栏

这是我准备华为od面试的专属专栏,我会把自己的解法更新在里面,我会尽量写清楚自己的思路以及多写关键注释,希望对阅读的人有帮助~~~

全部评论

相关推荐

在评审的菠萝蜜很成熟:舵轮步兵多写点呗,第一个项目更像单纯算法内容了
在找工作求抱抱
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务