waker0086 / HW-NKcode

https://www.nowcoder.com/exam/oj?page=1&pageSize=50&search=&tab=%E5%90%8D%E4%BC%81%E7%9C%9F%E9%A2%98&topicId=37
0 stars 0 forks source link

HJ29-字符串加解密 #中等#字符串 #25

Open waker0086 opened 2 years ago

waker0086 commented 2 years ago

https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a

waker0086 commented 2 years ago

思路

我的

def hj29():
    # 明文
    a = input()
    if a.isalnum():
        a = list(a)
        for i in range(len(a)):
            if a[i].isdigit():
                a[i] = str((int(a[i]) + 1) % 10)  # 取余保证10%10=0
            elif a[i] == 'Z':
                a[i] = 'a'
            elif a[i] == 'z':
                a[i] = 'A'
            elif a[i].isalpha() and a[i].islower():
                temp = ord(a[i]) + 1
                a[i] = chr(temp).upper()  # 字符串不能直接赋值。
            elif a[i].isalpha() and a[i].isupper():
                temp = ord(a[i]) + 1
                a[i] = chr(temp).lower()
        print(''.join(a))

    # 秘闻
    b = input()
    if b.isalnum():
        b = list(b)
        for i in range(len(b)):
            if b[i].isdigit():
                b[i] = str((int(b[i]) + 9) % 10)
            elif b[i] == 'a':
                b[i] = 'Z'
            elif b[i] == 'A':
                b[i] = 'z'
            elif b[i].isalpha() and b[i].islower():
                temp = ord(b[i]) - 1
                b[i] = chr(temp).upper()  # 字符串不能直接赋值。
            elif b[i].isalpha() and b[i].isupper():
                temp = ord(b[i]) - 1
                b[i] = chr(temp).lower()
        print(''.join(b))
    return

hj29()

映射

https://blog.nowcoder.net/n/ecaad3a4c83f411fb22a9e4849b6238d?f=comment

def check(a,b):
    L1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    L2 = "BCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyza1234567890"
    result = ""
    if b == 1:
        for i in a:
            result += L2[L1.index(i)]
    elif b == -1:
        for i in a:
            result += L1[L2.index(i)]
    return result
while True:
    try:
        print(check(input(),1))
        print(check(input(), -1))

    except:
        break

巧妙取余

def encodeAndDecode(string,mode):
    result = ''
    for i in string:
        code = ord(i)
        if 48 <= code <= 57:        #字符为数字时
            result += chr(48 + (code - 48 - mode) % 10)
        elif 65 <= code <= 90:      #字符为大写字母时
            result += chr(97 + (code - 65 - mode) % 26)
        elif 97 <= code <= 122:     #字符为小写字母时
            result += chr(65 + (code - 97 - mode) % 26)
        else:                       #其他字符
            result += i
    return result

try:
    while True:
        print(encodeAndDecode(input(),-1))
        print(encodeAndDecode(input(), 1))
except Exception:
    pass