PAT 1001. A+B Format (20)

题目:
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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

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

很明显是要把计算的结果每三个分组用逗号隔开,我的思路是把数字分开之后每三个加一个逗号,最后输出
因为对数字的分割我用的是对10取余和取整
所以每一次得到的都是最后一个尾数
所以输出的时候要从最后一个开始输出
所以我用到了栈这种数据结构
首先我们用python3实现一个栈

#定义栈的基本操作
class stack():
    def __init__(self):
        self.item= []
    def isEmpty(self):
        return len(self.item) ==0
    def push(self,item):
        self.item.append(item)
    def pop(self):
        return self.item.pop()
    def peek(self):
        if len(self.item)!=0:
            return self.item[len(self.item)-1]
        else:
            print('stack is empty')
    def size(self):
        return len(self.item)
数字的分割和每3个添加一个逗号
s= stack()
a = int(input())
b = int(input())

sum = a+b
i=0
sum0 = sum           #创建副本用来判断最后入栈(sum的第一位)是正数还是负数
while abs(sum) >= 10:   #利用绝对值来简化函数
    sum= abs(sum)
    remainder = sum % 10
    s.push(remainder)  #尾数入栈
    i+=1   #每三个加一个逗号
    if i == 3:
        s.push(',')
        i=0
    sum =sum //10  
    #print(sum)
if sum0>=0:   判断最后入栈(sum的最高位)的正负
    s.push(sum)
else:
    sum = -sum
    s.push(sum)
    print(sum)
for i in range(s.size()): #输出
    print(s.pop(),end='')

在这之中考虑过直接对1000取余和取整,每取一次加一个逗号,但是在类似10001这种数字的时候会发生取余只得1,而无法保留001这种错误,暂时只想到这种方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值