【kickstart 2018 round A】 Even Digits Python

BlueGrey_發表於2020-11-12

我寫的複雜一點,思路找到一個比它小 中最大的符合條件的數/ 比它大最小的符合條件的數,看那個跟原值接近

# -*- coding:utf-8 -*-
t=input("")
t=int(t)
a=[]
def bignum(num):
    length=len(num)
    flag=0
    for i in range(length):
        if(num[i]!=0 and num[i]!=2 and num[i]!=4 and num[i]!=6 and num[i]!=8):
            if(flag):
                num[i]=8
            else:
                flag=1
                num[i]=num[i]-1
        else:
            if(flag):
                num[i]=8

    return num
def smallnum(num):
    length=len(num)
    flag=0
    jw=0
    for i in range(length):
        if(num[i]!=0 and num[i]!=2 and num[i]!=4 and num[i]!=6 and num[i]!=8):
            if(flag):
                num[i]=0
            else:
                flag=1
                if(num[i]==9):
                    num[i]=0
                    j=i
                    j=j-1
                    if(j==-1):
                        jw=2
                    
                    else:
                        f=1
                        while(f and j>=0):
                            num[j]=num[j]+1
                            if(num[j]==9):
                                f=1
                                num[j]=0
                            else:
                                f=0
                                num[j]=num[j]+1
                            j=j-1
                        if(j<0 and f):
                            jw=2
                        

                else:
                    num[i]=num[i]+1
        else:
            if(flag):
                num[i]=0
    if(jw==2):
        num.insert(0,2)
    return num

for ca in range(1,t+1):
    a=[]
    t=t-1;
    num=input()
    num=int(num)
    temp=num
    while(num):
        a.insert(0,num%10)
        num=num/10
    t2=a[:]
    bn=bignum(t2)
    
    t2=a[:]
    sn=smallnum(t2)
    m1=0
    for i in bn:
        m1=m1*10+i
    m2=0
    for i in sn:
        m2=m2*10+i
    ans=min(temp-m1,m2-temp)
    print("Case #%d: %d"%(ca,ans))
    # print("Case #:%d"%bn)

看了別人寫的,比我寫的簡單  https://blog.csdn.net/sinat_32682001/article/details/106305486

思路就是遇到9時,答案只會在比它小的那一側,因為遇到9 比它大的話,會進位,會破壞掉前一個偶數,那麼差值就會變得更大

相關文章