当前位置:网站首页>Sword finger offer II 001. integer division

Sword finger offer II 001. integer division

2022-07-24 14:42:00 Learning machine:

subject :

 

 

idea :

Use subtraction instead of division

Pay attention to the border ! Be careful int Value range of !!! 

Code :

class Solution {
    public int divide(int a, int b) {
        boolean sign=true;
        int count=0;
        // Calculation int Maximum value range   minimum value 
        int max = (int)Math.pow(2,31);
        int min = -(int)Math.pow(2,31)-1;
        // Judge the boundary 
        if(a == min && b == -1)
            return max;
        if(a == min && b == 1)
            return min;
        if(b==min && a!=min)
            return 0;
        // If the sign is different, the sign bit is set to negative 
        if((a > 0 && b < 0) || (a < 0 && b > 0)){
            sign = false;
        }
        // take ab Convert all to positive numbers 
        a = a>0 ? a : -a;
        b = b>0 ? b : -b;
        // The negative boundary is taken as " back "
        if(a==min){
            a=max;
            // A special case   Still thinking about why ...
            if(b==2 || b==4)
                count++;
        }
        if(b==min){
            b=max;
        }
        // Judge again   Some use cases can directly jump out 
        if(a<b)
            return 0;
        // Use shift to achieve the effect of division 
        // Maximum shift 31 position 
        for(int i=31;i>=0;i--){
            // Determine whether to subtract 
            while((a>>i)>=b){
                a-=(b<<i);
                count+=(1<<i);
            }
        }
        // Set sign bit 
        if(sign)
            return count;
        else
            return -count;
    }
}

result :

原网站

版权声明
本文为[Learning machine:]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/203/202207211632595159.html