1. 题目
请实现整数数字的乘法、减法和除法运算,运算结果均为整数数字,
程序中只允许使用加法运算符和逻辑运算符,允许程序中出现正负常数,不允许使用位运算。
你的实现应该支持如下操作:
- Operations() 构造函数
- minus(a, b) 减法,返回a - b
- multiply(a, b) 乘法,返回a * b
- divide(a, b) 除法,返回a / b
示例:
Operations operations = new Operations();
operations.minus(1, 2); //返回-1
operations.multiply(3, 4); //返回12
operations.divide(5, -2); //返回-2
提示:
你可以假设函数输入一定是有效的,例如不会出现除法分母为0的情况
单个用例的函数调用次数不会超过1000次
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/operations-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
参考题解:把乘数和除数的 倍的结果 存起来,不断的加或者减
class Operations {
public:
Operations() {
}
int minus(int a, int b) {
return a+(-b);
}
int multiply(int a, int b) {
if(a==0 || b==0) return 0;
if(a==1) return b;
if(b==1) return a;
if(a== -1) return -b;
if(b== -1) return -a;
int negative = 0;
if(a < 0) negative += 1, a = -a;
if(b < 0) negative += 1, b = -b;
if(a > b) swap(a,b);// b*a
long temp = b;
vector<int> b_2, count;
int plus = 1;
while(temp <= INT_MAX)//b_2数组[b*1,b*2,b*4...]
{
b_2.push_back(temp);
count.push_back(plus);//b乘以几得到上面的数temp
temp += temp;
plus += plus;
}
int ans = 0;
for(int i = b_2.size()-1; i >= 0; i=minus(i,1))
{
while(a >= count[i])
{
ans += b_2[i];
a = minus(a,count[i]);//把a拆分
}
}
if(negative==1)
return -ans;
return ans;
}
int divide(int a, int b) {
if(a==0 || b==INT_MAX || b==INT_MIN) return 0;
if(b==1) return a;
if(b== -1) return -a;
int negative = 0;
if(a < 0) negative += 1, a = -a;
if(b < 0) negative += 1, b = -b;
if(a < b) return 0;
long temp = b;
vector<int> b_2, count;
int plus = 1;
while(a >= temp)
{
b_2.push_back(temp);//[b*1,b*2,b*4,...]
count.push_back(plus);//b乘以几得到上面的数temp
temp += temp;
plus += plus;
}
int ans = 0;
for(int i = b_2.size()-1; i >= 0; i=minus(i,1))
{
while(a >= b_2[i])
{
ans += count[i];//商+倍数
a = minus(a,b_2[i]);//把a减去b的倍数
}
}
if(negative==1)
return -ans;
return ans;
}
};
84 ms 15 MB