Java Solution Easy!!!!


  • 0
    A
    public class Solution {
        public int divide(int dividend, int divisor) {
            if (dividend == 0){
                return 0;
            }
            if (divisor == 0){
                return -1;
            }
            long res = 0;
            boolean flag = false;
            if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)){
                flag = true;
            }
            long tempDividend = Math.abs((long)dividend);
            long tempDivisor = Math.abs((long)divisor);
            if (tempDividend < tempDivisor){
                return 0;
            }
            while (tempDivisor <= tempDividend){
                long temp = tempDivisor;
                long count = 1; 
                while (temp <= tempDividend){
                    temp = temp << 1;
                    count = count << 1;
                }
                temp = temp >> 1;
                count = count >> 1;
                res += count;
                tempDividend -= temp;
            }
            if (flag == true){
                return (int)(0 - res);
            }
            if (res > Integer.MAX_VALUE){
                return Integer.MAX_VALUE; 
            }
            
            return (int)res;
        }
    }

Log in to reply
 

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