java - 不使用除法、乘法和 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;
}
}
解决方案
推荐阅读
- r - 从样本中抽取 d 个观测值 n 次并计算平均值
- vsphere - 如何将文件从 Windows XP 传输到 vSphere 5.5 中的虚拟机?
- swift - Swift 4 Firebase 在线状态更新
- java - 是否可以获得 putextra 的名称/标签?
- java - 从 Google PlayStore 下载应用程序时出现错误 _504 或错误 - 108 .. 代码中出现此错误的原因可能是什么?
- haskell - 为什么我必须从 build-deps 中删除 `ekg` 才能让 haskell stack/cabal 在 Windows 上找到我的 dll?
- javascript - Changing state with body width change in React
- io - MetaGraphs 加载和保存
- c# - How to design code for a given task following software design pattern?
- php - 在特定的 div 容器中显示 php 结果