开发者

Division using right shift for divider which not power of 2

I would like to perform the division of num by 60 which is not power of two using right shift operation. How do I do this?

If I wan开发者_如何学编程t num/64, I can do num >> 6 since 64 = 2^6

How do I do it for 60?


This should work:

public static final long divisionUsingShift(int x, int y) {
    int a, b, q, counter;

    q = 0;
    if (y != 0) {
        while (x >= y) {
            a = x >> 1;
            b = y;
            counter = 1;
            while (a >= b) {
                b <<= 1;
                counter <<= 1;
            }
            x -= b;
            q += counter;
        }
    }
    return q;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜