1. 程式人生 > >LeetCode-29. 兩數相除

LeetCode-29. 兩數相除

題目地址:https://leetcode-cn.com/problems/divide-two-integers/
思路:這題還是有點意思的,首先是隻能用int,然後不能用乘除mod。如果直接傻傻的用減法,那顯然超時。考慮用移位來操作,每次將除數逐漸翻倍至最接近被除數,然後將除數減去,直到被除數小於除數。由於負數範圍大1,所以全轉為負數可以避免一些特定情況的溢位,所以考慮全轉負數來做。此段程式碼為12ms。
AC程式碼:

class Solution {
public:
    int divide(int dividend, int divisor) {
        int max = 2147483647;
        int min = -2147483648;
        if(dividend == min && divisor == -1){
            return max;
        }
        int flag = 1;
        if(dividend<0 && divisor>0)
            flag = -1;
        if(dividend>0 && divisor<0)
            flag = -1;
        if(dividend>0)
            dividend*=-1;
        if(divisor>0)
            divisor*=-1;
        int ans = 0;
        while(dividend<=divisor){
            int temp = divisor;
            int res = 1;
            while(divisor >= dividend){
                if(divisor >= min>>1){
                    divisor = divisor<<1;
                    if(divisor>=dividend)
                    res = res<<1;
                    else{
                        divisor = divisor>>1;
                        break;
                    }
                    
                }else
                    break;
            }
            ans+=res;
            dividend-=divisor;
            divisor = temp;
        }
       
        return ans*flag;
    }
};