Leetcode029两数相除(二进制表示法)

地址

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;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_52934831/article/details/121422734
今日推荐