Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Divide Two Integers

Easy
0/40
Average time to solve is 10m
profile
Contributed by
44 upvotes
Asked in companies
CognizantSnapdealSAP Labs

Problem statement

You are given two integers, ‘dividend’ and ‘divisor’.


You are required to divide the integers without using multiplication, division, and modular operators.


Your task is to return the quotient after dividing ‘dividend’ by ‘divisor’.


Note :

In cases where the dividend is not perfectly divisible by the divisor, you are required to return the integer value of the quotient which is closer to zero.

For example - If the answer is '8.34', we return the integer part, i.e., '8'. Also, If the answer is '-2.67', we return the integer part, i.e., '-2'.

Assume we're dealing with a system that can only store integers in the 32-bit signed integer range: [2^31, 2^31-1]. If the quotient is higher than 2^31 - 1, return 2^31 - 1; if it is less than -2^31, return -2^31. 

For example :

If the answer is ‘9.333’, then return ‘9’, or if the answer is ‘-8.123’, then return ‘-8’.
Detailed explanation ( Input/output format, Notes, Images )
Input format:
The first input line contains two space-separated integers, ‘dividend’ and ‘divisor’. 
Output Format
The only line contains the result after division, following the above rules.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Sample Input 1:
10 3
Sample Output 1:
3
Explanation of sample input 1:
Given ‘dividend = 10’ and ‘divisor = 3’

So the division is ‘10/3 = 3.3333……’.

Return only integer part ‘3’
Sample Input 2:
7 -3
Sample Output 2:
-2
Constraints:
-10^9 <= dividend, divisor <= 10^9 
divisor != 0  

Time limit: 1 second
Hint

Change multiplicative property as a subtraction.

Approaches (2)
Using Subtraction

We can subtract the divisor from the dividend until the dividend is greater than the divisor. The quotient will be equal to the number of total subtractions performed.

 

Below is the detailed algorithm:

 

  1. Store the ‘IS_DIVIDEND_NEGATIVE = false’ and ‘IS_DIVISOR_NEGATIVE = false’.
  2. Check if the ‘DIVIDEND’ and ‘DIVISOR’ are positive or negative and update the values of ‘IS_DIVIDEND_NEGATIVE’ and  ‘IS_DIVISOR_NEGATIVE’.
  3. Iterate a while loop with ‘quotient = 0’
    • if ( ‘DIVIDEND’ > divisor) then:
      • (‘DIVIDEND’ = ‘DIVIDEND’ - ‘DIVISOR’) and (‘QUOTIENT’ = ‘QUOTIENT’  + 1).
  4. If both ‘IS_DIVIDEND_NEGATIVE’ and ‘IS_DIVISOR_NEGATIVE’ are of the same sign
    • Return ‘QUOTIENT’.
  5. Else, we need to make ‘quotient’ negative
    • Return ‘-1 * QUOTIENT’.
Time Complexity

0(N / M), where ‘N’ is ‘dividend’ and ‘M’ is ‘divisor’.

 

We are using a while loop, at max, it can iterate upto ‘dividend/divisor’ times.

Space Complexity

O(1).

 

Constant space is used.

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Divide Two Integers
All tags
Sort by
Search icon

Interview problems

most easy approch

int divideTwoInteger(int dividend, int divisor) {

    // Write your code here.

    int s = dividend / divisor;

    return s;

70 views
1 reply
0 upvotes

Interview problems

Easy python solution

def divideTwoInteger(a: int, b: int) -> int:

    sign = 1

    

    if a < 0 and b < 0:

        sign = 1

    elif a < 0 or b < 0:

        sign = -1

 

    a, b, quotient = abs(a), abs(b), 0

 

    while a >= b:

        a -= b

        quotient += 1

 

    return sign * quotient

74 views
0 replies
1 upvote

Interview problems

easy sol

only return statement I return d/s;

int divideTwoInteger(int d, int s) {

  // Write your code here.

  return d/s;

}

 

103 views
0 replies
0 upvotes

Interview problems

Easy approach

In this I used the basic logic like subtracting the number till it give less than 0 from that I will get the answer in easy way.

93 views
0 replies
0 upvotes

Interview problems

Optimal Solution PYT Code using Bit Manipulation | Time: O(log n * log n)

from typing import List

 

def divideTwoInteger(dividend: int, divisor: int) -> int:

 

    if dividend==divisor:

        return 1

    sign=True

    if (dividend>=0 and divisor<0) or (dividend<=0 and divisor>0):

        sign=False

    quo=0

    dividend=abs(dividend)

    divisor=abs(divisor)

    while dividend>=divisor:

        n=0

        while (dividend>=(divisor<<(n+1))):

            n+=1

        quo+=(1<<n)

        dividend-=(divisor<<n)

    if quo==(1<<31) and sign:

        return maxsize

    if quo==(1<<31) and not sign:

        return minsize

    return quo if sign else -quo

    

 

51 views
0 replies
1 upvote

Interview problems

C++ Optimised Approach Using Binary Search

int divideTwoInteger(int dividend, int divisor) {

    

        long int count = 0;

       long int sum = 0;

        

        while((sum + abs(divisor)) <= abs(dividend)){

            sum += abs(divisor);

            count++;

          }

        

      if((divisor > 0 && dividend > 0) || (divisor < 0 && dividend < 0))

           return count;

       else 

           return -count;

    

};

 

136 views
0 replies
0 upvotes

Interview problems

:)

int divideTwoInteger(int dividend, int divisor) {

    // Handle negative numbers

    int sign = 1;

    if (dividend < 0) {

        dividend = -1*dividend;

        sign = (-1)*sign;

    }

    if (divisor < 0) {

        divisor = -1*divisor;

        sign = -1*sign;

    }

    

    int count = 0;

    while (dividend >= divisor) {

        dividend -= divisor;

        count++;

    }

    

    return sign * count;

}

 

110 views
0 replies
0 upvotes

Interview problems

C++ Solution

int divideTwoInteger(int dividend, int divisor) {
	int dd=abs(dividend);
	int dr=abs(divisor);
	int count=0;
	while(dd>=dr){
		dd-=dr;
		count++;
	}

	if(divisor*dividend < 0) return (-count);
	else return count;
} 
209 views
0 replies
0 upvotes

Interview problems

Java Code

public class Solution{

    public static int divideTwoInteger(int dividend, int divisor) {

        // Write your code here.

 

        int sign = ((dividend<0) ^ (divisor<0)) ? -1 : 1;

        dividend = Math.abs(dividend);

        divisor = Math.abs(divisor);

 

        int res = 0;

 

        while(dividend>=divisor){

            int count = 0;

 

            while(dividend >= (divisor<<count+1)){

                count++;

            }

 

            res+= 1<<count;

            dividend -= divisor<<(count);

            

        }

         return sign*res;

    }

   

}

 

//Works on the logic of basic maths, that division means subs of a number from another multiple times. //Here we check that while divisor's multiple of 2 is less than the dividend. we inc the count, at last we add till what multiple of divisor is divisible. Later we subs the dividend with 3*multiple of 2.

java

340 views
0 replies
0 upvotes

Interview problems

What they want is this 👇 ( without using long or / )

#include<bits/stdc++.h>
int divideTwoInteger(int dividend, int divisor) {
	// Write your code here.
	 if (dividend == INT_MIN && divisor==-1) return INT_MAX;
        if(dividend==divisor)return 1;

        unsigned int n=abs(dividend),d=abs(divisor);
        bool neg=false;
        if(dividend <0 && divisor>=0)neg=true;
        else if(dividend >=0 && divisor<0)neg=true;
        unsigned int ans=0;
        while(n>=d){
            short count=0;
            while(n > (d<<count+1)){
                count++;
            }
            ans+=1<<count;
            n-=(d*(1<<count));
        }
        if(neg)ans*=-1;
        return ans;
} 
456 views
0 replies
1 upvote
Full screen
Console