给定两个正整数int a,int b,同时给定一个int type代表运算的类型,1为求a * b,0为求a / b,-1为求a - b,但规定只能使用加号,请编写程序返回计算结果,并保证数据合法且结果一定在int范围内。
测试样例:
1,2,1
返回:2
# -*- coding:utf-8 -*- class AddSubstitution: def calc(self, a, b, t): if t == -1: return self.minus(a, b) elif t == 1: return self.multiply(a, b) else: return self.divide(a, b) def minus(self, a, b): return self.negate(b) + a def multiply(self, a, b): result = sum([a for i in range(0, abs(b))]) if b < 0: result = self.negate(result) return result def divide(self, a, b): # a = xb 同乘法类似 absa = abs(a) absb = abs(b) x = 0 pro = 0 while pro + absb <= absa: pro += absb x += 1 if (a > 0 and b >0) or (a < 0 and b < 0): return x else: return self.negate(x) def negate(self, x): neg = 0 d = 1 if x < 0 else -1 while x != 0 : neg += d x += d return neg