Guest User

Untitled

a guest
Oct 19th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. /**
  2. * 29. Divide Two Integers
  3. * Divide two integers without using multiplication, division and mod operator.
  4. * If it is overflow, return MAX_INT.
  5. */
  6. class Solution {
  7. public int divide(int dividend, int divisor) {
  8. if (dividend == 0)
  9. return 0;
  10. else if (divisor == 1)
  11. return dividend;
  12. else if (divisor == -1) {
  13. dividend = ~dividend + 1;
  14. if (dividend == Integer.MIN_VALUE)
  15. return Integer.MAX_VALUE;
  16. else return dividend;
  17. } else if (dividend == divisor)
  18. return 1;
  19. boolean min = false;
  20. if (dividend == Integer.MIN_VALUE) {
  21. if (divisor == 2)
  22. return Integer.MIN_VALUE >> 1;
  23. if (divisor == -2)
  24. return ~(Integer.MIN_VALUE >> 1) + 1;
  25. //......
  26. if (divisor == 3)
  27. return -715827882;
  28. if (divisor == -3)
  29. return 715827882;
  30. //除以2以上都一样
  31. dividend = Integer.MAX_VALUE;
  32. min = true;
  33. }
  34. int quotient = 0;
  35. //都化成正数
  36. boolean divisorNegative = false;
  37. boolean dividendNegative = false;
  38. if (dividend < 0) {
  39. dividend = ~dividend + 1;
  40. dividendNegative = true;
  41. }
  42. if (divisor < 0) {
  43. divisor = ~divisor + 1;
  44. divisorNegative = true;
  45. }
  46. if (dividend < divisor)
  47. return 0;
  48.  
  49. int up = 0;
  50. //被除数是2的幂次数
  51. int temp = divisor - 1;
  52. if ((divisor & temp) == 0) {
  53. while ((temp & 0b1) == 0b1) {
  54. temp = temp >> 1;
  55. up++;
  56. }
  57. }
  58. if (up > 0) {
  59. quotient = dividend >> up;
  60. } else {
  61. //依次减
  62. while (dividend >= 0 && divisor > 0 || dividend <= 0 && divisor < 0) {
  63. dividend -= divisor;
  64. quotient++;
  65. }
  66. quotient--;
  67. }
  68. if (dividendNegative ^ divisorNegative)
  69. quotient = ~quotient + 1;
  70. if (min)
  71. quotient = ~quotient + 1;
  72. return quotient;
  73. }
  74. }
Add Comment
Please, Sign In to add comment