首页 > 试题广场 >

加法运算替代

[编程题]加法运算替代
  • 热度指数:9361 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定两个正整数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

发表于 2016-08-04 11:13:29 回复(0)

问题信息

难度:
1条回答 12805浏览

热门推荐

通过挑战的用户

查看代码