Click here to Skip to main content
15,916,463 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
import java.lang.Math;
public class Solution {
    public int divide(int dividend, int divisor) {
        int count = 0;
        boolean isNegative = false;
        if(dividend == divisor){
            return 1;
        } else if(divisor == 1){
            return dividend;
        } else if(dividend < 0 && divisor < 0){
          isNegative = false;
        } else if(dividend < 0 || divisor < 0){
            isNegative = true;
        } else if(dividend > Integer.MAX_VALUE){
            return Integer.MAX_VALUE;
        }
        if(dividend == Integer.MIN_VALUE && divisor == -1){
          return Integer.MAX_VALUE;
        }
        dividend = Math.abs(dividend);
        divisor = Math.abs(divisor);
            while(divisor <=dividend){
              dividend -= divisor;
              count++;
            }
        if(isNegative){
            count = count * -1;
        }
    return count;    
    }
}


What I have tried:

Here is my code for dividing without using the division, multiplication, and mod operator, but I'd like to see a more efficient way of dividing 2 integers without using these operators.
Posted
Updated 19-Aug-16 19:56pm
v2
Comments
[no name] 19-Aug-16 17:19pm    
And what is the point of using an alternative to the standard math operators?

1 solution

I take it this is your homework, hence the restrictions? :laugh:
There are several faster algorithms than repeated subtraction:
Division algorithm - Wikipedia, the free encyclopedia[^]
I prefer binary division, as it fits computers very nicely: Binary Division[^]
You should have been able to find these by yourself with a trivial Google.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900