- Divide Two Integers
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
题目解析:
1.题目已提示除数不为0,不需要考虑;
2.输入数值得范围已经告知,一定要考虑边界值;
3.被除数除以除数所得结果即为:被除数有几个除数,如15除以5得3,3即为返回值。
代码:
class Solution {
public:
int divide(int dividend, int divisor) {
if (dividend == INT_MIN && divisor == -1)//divisor不能为0,提干已有说明
return INT_MAX;
int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;//运算符或,相同则为1
long long a = abs((long long)dividend);//取绝对值运算,带上负数麻烦
long long b = abs((long long)divisor);
long long result = 0;//返回值
long long multiple[33], times[33];//倍数值数值,次数值数值
multiple[0] = b;
times[0] = 1;
int index = 0;
while (a>=multiple[index] && index < 33)//2得31次方,故为32,所以数值取33,此处得小于33
{
index++;
multiple[index] = multiple[index - 1] * 2;
times[index] = times[index - 1] + times[index - 1];//有图文解释
}
for (int i = index - 1; i >= 0; i--)
{
while (a >= multiple[i])
{
a -= multiple[i];
result += times[i];//有图文解释
}
}
result = (sign == 1) ? result : -result;
return (int)result;//(int)不能省,返回值是int型,不然会报错
}
long long ABS(long long a)//自定义abs函数
{
return a > 0 ? a : -a;
}
};
图文详解:
注意事项:
1.考虑到边界值问题:必须采用long long类型,否则边界值测试case会报错;
2.函数返回值为int类型,所以返回值必须转换为int型,否则报错;
性能:
这边看到网上大神,自定义了ABS函数,我这边对比了下,都可以测试通过,但是性能差很多。
原生abs函数性能:
自定义ABS函数性能:
总结:找到除数倍数得边界值即可得到答案,这就是思路。