Integer division without using the / or * operator

后端 未结 7 473
梦如初夏
梦如初夏 2021-01-14 15:34

I am going through an algorithms and datastructures textbook and came accross this question:

1-28. Write a function to perform integer division withou

相关标签:
7条回答
  • 2021-01-14 16:22

    I don't know what you mean by fast...and this seems like a basic question to test your thought process.

    A simple function can be use a counter and keep subtracting the divisor from the dividend till it becomes 0. This is O(n) process.

    int divide(int n, int d){
        int c = 0;
        while(1){
            n -= d;
            if(n >= 0)
                c++;
            else
                break;
        }
        return c;
    }
    

    Another way can be using shift operator, which should do it in log(n) steps.

        int divide(int n, int d){
        if(d <= 0)
            return -1;
        int k = d;
        int i, c, index=1;
        c = 0;
        while(n > d){
            d <<= 1;
            index <<= 1;
        }
        while(1){
            if(k > n)
                return c;
            if(n >= d){
                c |= index;
                n -= d;                
            }
            index >>= 1;
            d >>= 1;
        }
        return c;
    }
    

    This is just like integer division as we do in High-School Mathematics.

    PS: If you need a better explanation, I will. Just post that in comments.

    EDIT: edited the code wrt Erobrere's comment.

    0 讨论(0)
提交回复
热议问题