[PAT甲级] 1001 A+B Format [Python3]

题目描述:

Calculate a+b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

Input Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where −106≤a,b≤106. The numbers are separated by a space.

Output Specification:

For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

Sample Input:

-1000000 9

Sample Output:

-999,991

思路:

先得到两个输入整数的和,

如果这个整数小于4位(-999<= <=999),直接输出即可。

否则,用一个字符串保存无符号部分,将这个字符串反序之后开始从头遍历,每遍历三个字符就添加一个英文的逗号",",但是考虑到字符串长度刚好就是3的整数倍的特殊情况,这种情况下原始整数的第一位之前不能加",",相对应的反序后的字符串末尾也不能加",",所以要在对反序的字符串遍历时进行限制。最后将添加好","的字符串反序,并根据得到的两个整数的和的正负决定是否要在开头添加英文负号"-"。

源代码:

def format(a):
    ss = str(c)[::-1] if a>0 else str(c)[1:][::-1]
    s = ""
    for i in range(len(ss) - 1):
        s = s + ss[i]
        if (i + 1) % 3 == 0:
            s = s + ","
    s = s + ss[-1]

    return s[::-1] if a>0 else "-"+s[::-1]

if __name__ == "__main__":
    a,b = input().split(" ")
    c = int(a)+int(b)
    if -999<=c<=999:
        print(c)
    else:
        print(format(c))

提交结果:

[PAT甲级] 1001 A+B Format [Python3]_第1张图片

 

你可能感兴趣的:(机试刷题记录,算法,python,pat考试)