题目:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
链接:https://leetcode.com/problems/divide-two-integers/#/description
4/13/2017
没做出来,时间超了
以下是我没做出来的答案:
1 public class Solution { 2 public int divide(int dividend, int divisor) { 3 if (divisor == 0) return Integer.MAX_VALUE; 4 if (dividend == 0 || dividend > 0 && divisor > 0 && dividend < divisor || dividend < 0 && divisor < 0 && dividend > divisor) return 0; 5 if (divisor == 1) return dividend; 6 else if (divisor == -1) { 7 if (dividend == Integer.MIN_VALUE) return Integer.MAX_VALUE; 8 return -dividend; 9 } 10 if (dividend == divisor) return 1; 11 else if (dividend == -divisor) return -1; 12 13 int sign = 1; 14 15 if (dividend > 0 && divisor < 0) { 16 divisor = -divisor; 17 sign = -1; 18 } else if (dividend < 0 && divisor > 0) { 19 dividend = -dividend; 20 sign = -1; 21 } 22 23 int initDivisor = divisor; 24 int quotient = 0; 25 int times = 0; 26 27 while (dividend >= initDivisor) { 28 while (dividend > divisor) { 29 divisor <<= 1; 30 if (times == 0) times = 1; 31 else times <<= 1; 32 } 33 quotient += times; 34 dividend -= divisor >> 1; 35 divisor = initDivisor; 36 times = 0; 37 } 38 return sign == 1? quotient: -quotient; 39 } 40 }
需要再研究这道题,可以参考:
http://www.cnblogs.com/yrbbest/p/4435159.html
更多讨论:
https://discuss.leetcode.com/category/37/divide-two-integers
原文:http://www.cnblogs.com/panini/p/6706919.html