Iam_Sandeep

Divide Two Integers with out using multiplication

Jun 14th, 2022
1,092
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. class Solution:
  2.     def divide(self, dividend: int, divisor: int) -> int:
  3.        
  4.         ans=0
  5.        
  6.        
  7.         sign=(dividend<0)==(divisor<0)
  8.         divisor,dividend=abs(divisor),abs(dividend)
  9.         ```
  10.         Here we will copy divisor to tsum and every time we double tsum and checks whether it
  11.         has reached dividend or not.
  12.         If it reaches dividend we add current quotient to our answer and will make new dividiend
  13.         from old divident that has eaten by current quotient
  14.         ```
  15.         tsum=divisor
  16.         while tsum<=dividend:
  17.             q=1
  18.             while tsum+tsum<=dividend:
  19.                 q=q+q
  20.                 tsum=tsum+tsum
  21.             ans+=q
  22.             dividend=dividend-tsum
  23.             tsum=divisor
  24.         ans=ans if sign else -ans
  25.         ```
  26.         Since question has said range is in given 32 bits.
  27.         max 32 bit value is 2**31-1
  28.         min 32 bit value is -2**31
  29.         ```
  30.         return min(max(-2**31, ans), 2**31-1)
Advertisement
Add Comment
Please, Sign In to add comment