|
| 1 | +// Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. |
| 2 | +// |
| 3 | +// The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, |
| 4 | +// and -2.7335 would be truncated to -2. |
| 5 | +// My method used Long Division, here is the source "https://en.wikipedia.org/wiki/Long_division" |
| 6 | + |
| 7 | +package com.thealgorithms.maths; |
| 8 | + |
| 9 | +public class LongDivision { |
| 10 | +public static int divide(int dividend, int divisor) { |
| 11 | + long new_dividend_1 = dividend; |
| 12 | + long new_divisor_1 = divisor; |
| 13 | + |
| 14 | + if (dividend < 0) { |
| 15 | + new_dividend_1 = new_dividend_1 * -1; |
| 16 | + } |
| 17 | + if (divisor < 0) { |
| 18 | + new_divisor_1 = new_divisor_1 * -1; |
| 19 | + } |
| 20 | + |
| 21 | + if (dividend == 0 || new_dividend_1 < new_divisor_1) { |
| 22 | + return 0; |
| 23 | + } |
| 24 | + |
| 25 | + StringBuilder answer = new StringBuilder(); |
| 26 | + |
| 27 | + String dividend_string = "" + new_dividend_1; |
| 28 | + int last_index = 0; |
| 29 | + |
| 30 | + String remainder = ""; |
| 31 | + |
| 32 | + |
| 33 | + for (int i = 0; i < dividend_string.length(); i++) { |
| 34 | + String part_v1 = remainder + "" + dividend_string.substring(last_index, i + 1); |
| 35 | + long part_1 = Long.parseLong(part_v1); |
| 36 | + if (part_1 > new_divisor_1) { |
| 37 | + int quotient = 0; |
| 38 | + while (part_1 >= new_divisor_1) { |
| 39 | + part_1 = part_1 - new_divisor_1; |
| 40 | + quotient++; |
| 41 | + } |
| 42 | + answer.append(quotient); |
| 43 | + } else if (part_1 == new_divisor_1) { |
| 44 | + int quotient = 0; |
| 45 | + while (part_1 >= new_divisor_1) { |
| 46 | + part_1 = part_1 - new_divisor_1; |
| 47 | + quotient++; |
| 48 | + } |
| 49 | + answer.append(quotient); |
| 50 | + } else if (part_1 == 0) { |
| 51 | + answer.append(0); |
| 52 | + } else if (part_1 < new_divisor_1) { |
| 53 | + answer.append(0); |
| 54 | + } |
| 55 | + if (!(part_1 == 0)) { |
| 56 | + remainder = String.valueOf(part_1); |
| 57 | + }else{ |
| 58 | + remainder = ""; |
| 59 | + } |
| 60 | + |
| 61 | + last_index++; |
| 62 | + } |
| 63 | + |
| 64 | + if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) { |
| 65 | + try { |
| 66 | + return Integer.parseInt(answer.toString()) * (-1); |
| 67 | + } catch (NumberFormatException e) { |
| 68 | + return -2147483648; |
| 69 | + } |
| 70 | + } |
| 71 | + try { |
| 72 | + return Integer.parseInt(answer.toString()); |
| 73 | + } catch (NumberFormatException e) { |
| 74 | + return 2147483647; |
| 75 | + } |
| 76 | + |
| 77 | + } |
| 78 | +} |
0 commit comments