Divide two integers without using multiplication , division and mod operator | Java implementation to Divide two integers without using multiplication , division and mod operator ; Function to divide a by b and return floor value it ; Calculate sign of divisor i . e . , sign will be negative only iff either one of them is negative otherwise it will be positive ; remove sign of operands ; Initialize the quotient ; test down from the highest bit and accumulate the tentative value for valid bit 1 << 31 behaves incorrectly and gives Integer Min Value which should not be the case , instead 1L << 31 works correctly . ; if the sign value computed earlier is - 1 then negate the value of quotient ; Driver code
import java . io . * ; import java . util . * ; class GFG { public static long divide ( long dividend , long divisor ) { long sign = ( ( dividend < 0 ) ^ ( divisor < 0 ) ) ? - 1 : 1 ; dividend = Math . abs ( dividend ) ; divisor = Math . abs ( divisor ) ; long quotient = 0 , temp = 0 ; for ( int i = 31 ; i >= 0 ; -- i ) { if ( temp + ( divisor << i ) <= dividend ) { temp += divisor << i ; quotient |= 1L << i ; } } if ( sign == - 1 ) quotient = - quotient ; return quotient ; } public static void main ( String args [ ] ) { int a = 10 , b = 3 ; System . out . println ( divide ( a , b ) ) ; int a1 = 43 , b1 = - 8 ; System . out . println ( divide ( a1 , b1 ) ) ; } }