地址
https://leetcode-cn.com/problems/divide-two-integers/submissions/
描述
思想
代码
class Solution {
public:
int divide(int x, int y) {
typedef long long LL;
LL res=0;
//用来存放2^0*y、2^1*y、......2^30*y
vector <LL> exp;
//首先将x和y都当做正数处理
bool pos=false ;//pos =true ,代表答案需要取负数
if(x<0 &&y>0||x>0&&y<0) pos=true;
LL a=abs((LL)x), b=abs((LL)y);
for(LL i=b;i<=a;i=i+i) exp.push_back(i);
for(int i=exp.size()-1;i>=0;i--){
if(a>=exp[i]){
a-=exp[i];
//这里加上(LL)是为了防止1左移后溢出。
res+=(LL) 1<<i;
}
}
if(pos) res=-res;
if(res<INT_MIN||res>INT_MAX) return INT_MAX;
return res;
}
};