Divide Two Integers in C++


Suppose we have two integers dividend and divisor. We have to divide two integers without using multiplication, division, and mod operator. Return the quotient after dividing the dividend by divisor. The integer division should truncate toward zero. Both of the inputs are integers

So if the given inputs are dividend = 7, divisor = -3, then output will be -2.

To solve this, we will follow these steps −

  • Taking two arguments x and y it indicates x divides y
  • if x < -Infinity and y = 1, then return infinity
  • a := |x|, b := |y| and ans := 0
  • while a – b >= 0
    • p := 0
    • while a – (left shifted b (left shifted 1 p times)) >= 0
      • p := p + 1
    • a := a – (left shift b, p times)
    • ans := ans + left shift 1 p times
  • if x > 0 is true and y > 0 is also true, then return ans, otherwise return (– ans)

Example(C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
   int divide(int l, int y) {
      if(l <= INT_MIN && y == -1)return INT_MAX;
      lli a = labs(l);
      lli b = labs(y);
      lli ans = 0;
      while(a-b >= 0){
         int x = 0;
         while(a-(b << 1 << x) >= 0){
            x++;
         }
         a -= b<<x;
         ans += 1<<x;
      }
      return (l>0)== (y>0)?ans:-ans;
   }
};
main(){
   Solution ob;
   cout << ob.divide(40, 3);
}

Input

40
3

Output

13

Updated on: 27-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements