Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

Divide two integers without using multiplication, division and mod operator

public int divide(int AA, int BB) {
    // Edge case first.    
    if (BB == -1 && AA == Integer.MIN_VALUE){
        return Integer.MAX_VALUE;   // Very Special case, since 2^31 is not inside range while -2^31 is within range.
    }
    long B = BB;
    long A = AA;

    int sign = -1;
    if ((A<0 && B<0) || (A>0 && B>0)){
        sign = 1;
    }
    if (A < 0) A = A * -1;
    if (B < 0) B = B * -1;

    int ans = 0;
    long currPos = 1; // necessary to be long. Long is better for left shifting.
    while (A >= B){
        B <<= 1; currPos <<= 1;
    }
    B >>= 1; currPos >>= 1;
    while (currPos != 0){
        if (A >= B){
            A -= B;
            ans |= currPos;
        }
        B >>= 1; currPos >>= 1;
    }
    return ans*sign;
}
Comment

PREVIOUS NEXT
Code Example
Java :: java input - how to read a string 
Java :: actuator spring boot 
Java :: java list 
Java :: équivalent setTimeInterval java 
Java :: java difference hashmap hashtable 
Java :: import javafx 
Java :: string palindrome in java 
Java :: split with multiple condition in java 
Java :: convert class to java command line 
Java :: type of exception in java 
Java :: If you are using the git profile, you need to set a Git URI in your configuration. If you have set spring.cloud.config.server.bootstrap=true, you need to use a composite configuration. 
Java :: java stringbuilder setcharat 
Java :: Java Create an InputStream 
Java :: what is exception in java 
Java :: use of randomAccessfile() in java 
Java :: spiral traversal of matrix leetcode 
Java :: how to change toolbar name in android studio 
Java :: combinations in java 
Java :: R8: java.lang.OutOfMemoryError: GC overhead limit exceeded react-native 
Java :: Java Exceptions - Try...Catch 
Java :: Android Number Picker format JAVA 
Java :: nextint java 
Java :: finding length of arrays in java 
Java :: exceptions in java 
Java :: Delete Specials Caractères from a String in java 
Java :: isnumeric matches in java 
Java :: calendar check if month is 30 days 
Java :: reverse arraylist java recursion 
Java :: java border 
Java :: how to use setonclicklistener from custom view in android 
ADD CONTENT
Topic
Content
Source link
Name
7+1 =