AcWing 791. 高精度加法
代码部分(Python3)
def add(x,y):if len(x) < len(y): return add(y,x)x = x[::-1]y = y[::-1]t = 0res = []for i in range(len(x)):t += x[i]if i < len(y):t += y[i]res.append(t %10)t //= 10if t != 0: res.append(t)return res[::-1]if __name__ == "__main__":x = list(map(int,input()))y = list(map(int,input()))res = add(x,y)print("".join(map(str,res)))
AcWing 792. 高精度减法
代码部分(Python3)
def cmp(x,y):if len(x) != len(y): return len(x) > len(y)for i, j in zip(x,y):if i != j: return i > jreturn Truedef sub(x,y):x = x[::-1]y = y[::-1]t = 0res = []for i in range(len(x)):t = x[i] - tif i < len(y):t -= y[i]res.append(t %10)if t < 0: t = 1else: t = 0while len(res) > 1 and res[-1] == 0: res.pop()return res[::-1]if __name__ == "__main__":x = list(map(int,input()))y = list(map(int,input()))if cmp(x,y):res = sub(x,y)print("".join(map(str,res)))else:res = sub(y,x)print("-"+"".join(map(str,res)))
AcWing 793. 高精度乘法
代码部分(Python3)
def mul(x,y):res = []r = 0x = x[::-1]for i in range(len(x)):c = x[i] * y + rres.append(c % 10)r = c//10if r != 0: res.append(r)while len(res) > 1 and res[-1] == 0: res.pop()return res[::-1]if __name__ == "__main__":x = list(map(int,input()))y = int(input())c = mul(x,y)print("".join(map(str,c)))
AcWing 794. 高精度除法
代码部分(Python3)
def div(x,y):r = 0res = []for i in range(len(x)):c = r * 10 + x[i]res.append(c // y)r = c % yres = res[::-1]while len(res) > 1 and res[-1] == 0: res.pop()return res[::-1], rif __name__ == "__main__":x = list(map(int,input()))y = int(input())res, r = div(x,y)print("".join(map(str,res)))print(r)
规律总结
- 加法,减法,乘法要对输入值逆序
- 减法,乘法,除法在函数最后一步要有0去除,即使用while循环
- 减法要判断输入x与y的大小
- 加法:引入r表示进位,每次计算时是x[i] + y[i] + r,r由和整除10得到
- 减法:引入r表示借位,每次计算时是x[i] - y[i] - r,r=1或0
- 乘法:引入r表示上一步的高位,每次计算时是x[i] * y[i] + r,r由结果整除10得到
- 除法:引入r表示上一步的余数,每次计算时r*10+x[i],r由结果模y得到