C# solution without long or unsigned


  • 0
    H
    public class Solution {
        public int Divide(int dividend, int divisor) {
            if(divisor == 0 || (dividend == Int32.MinValue && divisor == -1))   return Int32.MaxValue;
            bool flag = dividend > 0 ^ divisor > 0;
            if(dividend > 0)    dividend = 0 - dividend;
            if(divisor > 0)     divisor = 0 - divisor;
            int[] nums = new int[32], counts = new int[32];
            nums[0] = divisor;
            counts[0] = -1;
            int i = 1;
            int temp = nums[0] << 1;
            while(temp < 0 && temp >= dividend)
            {
                nums[i] = temp;
                counts[i] = counts[i - 1] << 1;
                temp = nums[i++] << 1;
            }
            int result = 0;
            while(--i >= 0)
            {
                if(dividend <= nums[i])
                {
                    result += counts[i];
                    dividend -= nums[i];
                }
            }
            return flag ? result : 0 - result;
        }
    }
    

Log in to reply
 

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