mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-27 06:23:08 +08:00
@ -1,17 +1,19 @@
|
||||
// Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
|
||||
// Given two integers dividend and divisor, divide two integers without using multiplication,
|
||||
// division, and mod operator.
|
||||
//
|
||||
// The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8,
|
||||
// and -2.7335 would be truncated to -2.
|
||||
// My method used Long Division, here is the source "https://en.wikipedia.org/wiki/Long_division"
|
||||
// The integer division should truncate toward zero, which means losing its fractional part.
|
||||
// For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. My
|
||||
// method used Long Division, here is the source
|
||||
// "https://en.wikipedia.org/wiki/Long_division"
|
||||
|
||||
package com.thealgorithms.maths;
|
||||
|
||||
public class LongDivision {
|
||||
public static int divide(int dividend, int divisor) {
|
||||
public static int divide(int dividend, int divisor) {
|
||||
long new_dividend_1 = dividend;
|
||||
long new_divisor_1 = divisor;
|
||||
|
||||
if(divisor == 0){
|
||||
if (divisor == 0) {
|
||||
return 0;
|
||||
}
|
||||
if (dividend < 0) {
|
||||
@ -32,7 +34,6 @@ public static int divide(int dividend, int divisor) {
|
||||
|
||||
String remainder = "";
|
||||
|
||||
|
||||
for (int i = 0; i < dividend_string.length(); i++) {
|
||||
String part_v1 = remainder + "" + dividend_string.substring(last_index, i + 1);
|
||||
long part_1 = Long.parseLong(part_v1);
|
||||
@ -57,7 +58,7 @@ public static int divide(int dividend, int divisor) {
|
||||
}
|
||||
if (!(part_1 == 0)) {
|
||||
remainder = String.valueOf(part_1);
|
||||
}else{
|
||||
} else {
|
||||
remainder = "";
|
||||
}
|
||||
|
||||
@ -76,6 +77,5 @@ public static int divide(int dividend, int divisor) {
|
||||
} catch (NumberFormatException e) {
|
||||
return 2147483647;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user