Divide two integers without using multiplication, division and mod operator.
Https://oj.leetcode.com/problems/divide-two-integers/
Train of Thought 1: we can only use subtraction, minus divisor and Tots in sequence, and it definitely times out.
Idea 2: each time minus n times the divisor, the result is also added n times, so we need to increase the divisor by N times.
- Extend int to long to prevent overflow.
- Multi [I] stores the case where the divisor is increased by I times and then subtracted by the divisor.
- Negative number processing.
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)); }}
Refer:
Http://blog.csdn.net/doc_sgl/article/details/12841741
Http://blog.csdn.net/linhuanmars/article/details/20024907