[leetcode] Divide Two Integers
Divide two integers without using multiplication, division and mod operator.
https://oj.leetcode.com/problems/divide-two-integers/
思路1:看样只能用减法了,依次减去除数,TOTS,肯定超时。
思路2:每次减去N倍的除数,结果也加上N次,因此我们需要将除数扩大N倍。
- int扩展成long防止溢出。
- multi[i]存储除数扩大i倍的情况,然后用被除数减。
- 负数处理。
public class Solution { public int divide(int dividend, int divisor) { if (dividend == 0 || divisor == 1) return dividend; long divid = dividend; long divis = divisor; boolean neg = false; int result = 0; if (dividend < 0) { neg = !neg; divid = -divid; } if (divisor < 0) { neg = !neg; divis = -divis; } long[] multi = new long[32]; for (int i = 0; i < 32; i++) multi[i] = divis << i; for (int i = 31; i >= 0; i--) { if (divid >= multi[i]) { result += 1 << i; divid -= multi[i]; } } return (neg ? -1 : 1) * result; } public static void main(String[] args) { System.out.println(new Solution().divide(5, 2)); System.out.println(new Solution().divide(5, -2)); System.out.println(new Solution().divide(100, 2)); System.out.println(new Solution().divide(222222222, 2)); System.out.println(new Solution().divide(-2147483648, 2)); } }
第二遍记录:
结果可能溢出,考虑-2147483648 除以 -1 的情况。
除数为0的情况,要抛出异常么。
第三遍记录:
public int divide(int dividend, int divisor) { if (dividend == 0 || divisor == 1) return dividend; long divid = dividend; long divis = divisor; boolean neg = false; int result = 0; if (dividend < 0) { neg = !neg; divid = -divid; } if (divisor < 0) { neg = !neg; divis = -divis; } for (int i = 31; i >= 0; i--) { long tmp = divis << i; if (divid >= tmp) { result += 1 << i; divid -= tmp; } } return (neg ? -1 : 1) * result; }
参考: