Divide two integers without using multiplication, division and mod operator.
原题链接:https://oj.leetcode.com/problems/divide-two-integers/
题目:两数相除,不使用乘法、除法和模运算。
思路:只能使用减法了,还有位运算可以当成乘除法来用。开始做的时候用的是单倍的减法,即被除数一次次地减除数,直到差为0,这样超时了,后来采用成倍的减法来做,Accepted。
public int divide(int dividend, int divisor) {
long absdividend = Math.abs((long) dividend);
long absdivisor = Math.abs((long) divisor);
int quotient = 0;
while (absdividend >= absdivisor) {
long temp = absdivisor;
for (int i = 1; absdividend >= temp; i <<= 1, temp <<= 1) {
absdividend -= temp;
quotient += i;
}
}
return ((dividend < 0) ^ (divisor < 0)) ? -quotient : quotient;
}

475

被折叠的 条评论
为什么被折叠?



