两数相除 (Divide Two Integers)

 

思路:暴力:四种正负情况处理+除数为正负1边界处理

// @Title: 两数相除 (Divide Two Integers)
// @Author: qisiii
// @Date: 2024-10-12 20:09:37
// @Runtime: 1961 ms
// @Memory: 39.9 MB
// @comment: 暴力:四种正负情况处理+除数为正负1边界处理
// @flag: RED
class Solution {
    public int divide(int dividend, int divisor) {
        if (dividend == 0) {
            return 0;
        }
        int count = 0;
        if(divisor==1){
            return dividend;
        }
        if(divisor==-1){
            if(dividend==Integer.MAX_VALUE){
                return -Integer.MAX_VALUE;
            }else if(dividend==Integer.MIN_VALUE){
                return Integer.MAX_VALUE;
            }
        }
        if ((dividend > 0 && divisor > 0)) {
            while (dividend >= divisor) {
                dividend -= divisor;
                count++;
            }
            return count;
        } else if (dividend < 0 && divisor < 0) {
            while (dividend <= divisor) {
                dividend -= divisor;
                count++;
            }
            return count;
        }else if (dividend > 0) {
            while (dividend > 0) {
                dividend += divisor;
                count++;
            }
            if(dividend<0){
                count--;
            }
            return -count;
        } else {
            while (dividend < 0) {
                dividend += divisor;
                count++;
            }
            if(dividend>0){
                count--;
            }
            return -count;
        }
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18