[leetCode 丶 20241203] 29. 两数相除

原题:

https://leetcode.cn/problems/divide-two-integers/description/


描述:

描述


个人版答案

执行用时: 0 ms 执行内存消耗: 40.04 M

class Solution { public int divide(int dividend, int divisor) { if(dividend == -2147483648 && divisor == -1){ return 2147483647; } return dividend / divisor; } }

优秀解法

执行耗时: 0 ms

class Solution { public int divide(int dividend, int divisor) { // 考虑被除数为最小值的情况 if (dividend == Integer.MIN_VALUE) { if (divisor == 1) { return Integer.MIN_VALUE; } if (divisor == -1) { return Integer.MAX_VALUE; } } // 考虑除数为最小值的情况 if (divisor == Integer.MIN_VALUE) { return dividend == Integer.MIN_VALUE ? 1 : 0; } // 考虑被除数为 0 的情况 if (dividend == 0) { return 0; } // 一般情况,使用二分查找 // 将所有的正数取相反数,这样就只需要考虑一种情况 boolean rev = false; if (dividend > 0) { dividend = -dividend; rev = !rev; } if (divisor > 0) { divisor = -divisor; rev = !rev; } int left = 1, right = Integer.MAX_VALUE, ans = 0; while (left <= right) { // 注意溢出,并且不能使用除法 int mid = left + ((right - left) >> 1); boolean check = quickAdd(divisor, mid, dividend); if (check) { ans = mid; // 注意溢出 if (mid == Integer.MAX_VALUE) { break; } left = mid + 1; } else { right = mid - 1; } } return rev ? -ans : ans; } // 快速乘 public boolean quickAdd(int y, int z, int x) { // x 和 y 是负数,z 是正数 // 需要判断 z * y >= x 是否成立 int result = 0, add = y; while (z != 0) { if ((z & 1) != 0) { // 需要保证 result + add >= x if (result < x - add) { return false; } result += add; } if (z != 1) { // 需要保证 add + add >= x if (add < x - add) { return false; } add += add; } // 不能使用除法 z >>= 1; } return true; } }

个人解题思路与优秀答案解析

题目分析及个人版思路

  1. 秒了, 今儿的评论区可以检查有没有看文章. 哈哈哈哈
  2. 本来写了一个连续减法, 然后爆了...一气之下, 直接开大~ 稳准狠!

进阶版思路
思路大概是减数倍增和位运算...看代码吧~ 反正没有我的0ms快