PTA 14 string to decimal integer

 

Enter a string ending with #. This question requires filtering out all non-hexadecimal characters (case-insensitive) to form a new string representing a hexadecimal number, and then convert it to a decimal number. output. If the character "-" is present before the first hexadecimal character, the number is negative.

Input format:

Input is given a non-empty string terminated with # on one line.

Output format:

Output the converted decimal number on one line. The title guarantees that the output is in the range of a long integer.

Input sample:

+-P-xf4+-1!#

Sample output:

-3905
st = input()
ss = st.lower() # 转换成小写
rs = ''
shuma = '0123456789abcdef'
for i in ss: # 过滤非十六进制字符
    if i in shuma:
        rs+=i
# 判断正负,如果为正,fuhao=1,否则fuhao=-1
fuhao = 1 
for i in ss:
    if i in shuma: # 如果第一个数是十六进制字符,则不是负,直接中止循环
        break
    if i =='-': # 如果第一个数是‘-’,则结果为负,循环中止
        fuhao=-1
        break
 ##注意须考虑rs为空的情形,返回0
if rs =='':
    print(0)
else :
    r=fuhao*int(rs,16)    
    print(r)

 operation result

 

Guess you like

Origin blog.csdn.net/weixin_58707437/article/details/127945410