Can anyone solve this without long long (int_64) trick?


  • 0
    E

    Can anyone solve this problem without long long (int_64) trick? What will you do if the inputs are changed to be long long type?


  • 1
    Y
    INT_MAX = 2147483647
    INT_MIN = -INT_MAX - 1
    
    def divide(a, b):
        sign = 1 if a >> 32 ^ b >> 32 else 0
    
        if a < 0:
            a = ~a + 1
        if b < 0:
            b = ~b + 1
    
        if a < b:
            return 0
    
        if a == b:
            return 1 if not sign else -1
    
        res = 0
        while a >= b:
            m = 1
            while (m * b) << 1 < a:
                m <<= 1
            a -= m * b
    
            if not sign and res > INT_MAX - m:
                return INT_MAX
            elif sign and res > INT_MAX - m + 1:
                return INT_MIN
    
            res += m
    
        return res if not sign else ~res + 1
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.