29.两数相除
题目链接
看题目名以为是要我写大整数除法,打算扔了,看了题以后发现只是不让用*/%
大概把快速乘法反着写一写就可以了。
class Solution {
public:
typedef long long LL;
int sgn(int a){return a>0;}
int divide(int dividend, int divisor) {
LL ans = 0,mx = 1;
LL sn = (sgn(dividend)^sgn(divisor))?-1:1;
LL ldividend = abs((LL)dividend);
LL ldivisor = abs((LL)divisor);
LL p = ldivisor;
while(ldividend>=p){
p<<=1;
mx<<=1;
}
while(p>ldivisor){
p>>=1;
mx>>=1;
if(ldividend>=p){
ans+=mx;
ldividend-=p;
}
}
ans = ans*sn;
return (ans<=INT_MAX&&ans>=INT_MIN)?ans:INT_MAX;
}
};