首页 > 解决方案 > 不使用除法、乘法和 mod 运算符将两个整数相除,位操作循环中断方程中的缺陷

问题描述

这个问题已经在这里回答了。

我的查询是,遵循方法 1 有效,但是它的变化,即方法 2 没有,而是它给出了超出的时间限制。我不知道为什么。我使用interviewbit portal 来解决这个问题,这里是leetcode

问题是

for(; i<32 && ((B<<i)-A <=0); i++) {
}

有效,但是

for(; i<32 && (B<<i)<=A; i++) {
}

不起作用,而是给出了 Time Limit Exceeds 问题。

方法一

public class Solution {
    public int divide(int A, int B) {

        //Base Cases
        if (B == 1) {
            return A;
        }
        if (A == Integer.MIN_VALUE && B == -1) {
            return Integer.MAX_VALUE;
        }

        boolean neg = false;
        if((A<0 && B>0) || (A>0 && B<0)) neg=true;
        A = A==Integer.MIN_VALUE ? Integer.MAX_VALUE : Math.abs(A);
        B = Math.abs(B);
        if(A<B) return 0;

        int res=0;
        while(A>=B) {
            int i=0;

            for(; i<32 && ((B<<i)-A <=0); i++) {
            }

            i--;
            res+=(1<<i);
            A-=(B<<i);
        }
      return neg? res*-1 : res;
    }
}

方法二

public class Solution {
    public int divide(int A, int B) {

        //Base Cases
        if (B == 1) {
            return A;
        }
        if (A == Integer.MIN_VALUE && B == -1) {
            return Integer.MAX_VALUE;
        }

        boolean neg = false;
        if((A<0 && B>0) || (A>0 && B<0)) neg=true;
        A = A==Integer.MIN_VALUE ? Integer.MAX_VALUE : Math.abs(A);
        B=Math.abs(B);
        if(A<B) return 0;
        int res=0;

        while(A>=B) {
            int i=0;

            for(; i<32 && (B<<i)<=A; i++) {
            }

            i--;
            res+=(1<<i);
            A-=(B<<i);
        }
      return neg? res*-1 : res;
    }
}

标签: javaalgorithmbit-manipulation

解决方案


推荐阅读