java - 不使用 / ,* 或 % 将 2 个数字相除
问题描述
假设我们假设 a=16 b=3
- 首先,我试图找到当我乘以 3 然后从 16 减去时得到的 x 将得到最小差异
- 16-3<<0 =>16-(3*1) -- 16-3<<1 =>16-(3*2) -- 16-3<<2 =>16-(3*4) - - 16-3<<3 =>16-(3*8)
- 在 x=3 while 循环将失败
- res = 4 和 a 将变为 4
- 现在再次while循环将开始
- 4-3<<0 =>4-(3*1) -- 4-3<<1 =>4-(3*2)
- 在 x=1 while 循环将失败
- 资源 = 4+1
请帮助我解决复杂性,因为我的时间限制已超过
public class Solution {
public int divide(int dividend, int divisor) {
if(dividend == Integer.MIN_VALUE && divisor == -1){
return Integer.MAX_VALUE;
}
int a = Math.abs(dividend);
int b = Math.abs(divisor);
int res = 0;
while(a - b >= 0){
int x = 0;
while( (a - (b << x)) >= 0){
x++;
}
res += 1 << (x-1);
a -= b << (x-1);
// System.out.println(res+" "+x+" "+a);
}
return (dividend >= 0) == (divisor >= 0) ? res :-res;
}
}
解决方案
简化程序的一种方法是x
只搜索一次,然后x
在每个循环中减少 1:
public int divide(int dividend, int divisor) {
if(dividend == Integer.MIN_VALUE && divisor == -1){
return Integer.MAX_VALUE;
}
int a = Math.abs(dividend);
int b = Math.abs(divisor);
int res = 0;
int x = 0;
while(a - (b << x) >= 0) {
x++;
}
x--;
while(a >= b) {
int c = a - (b << x);
if(c >= 0) {
res += 1 << x;
a = c;
}
x--;
}
return (dividend >= 0) == (divisor >= 0) ? res :-res;
}
推荐阅读
- django - 在Django Rest Api上按下POST按钮时如何调用函数
- listview - 如何在 Flutter ListView Builder 中移除或管理空间?
- regex - 在模式匹配之间提取值
- php - Laravel 注册表单不返回任何错误
- c# - 创建与类属性具有相同类型的列表
- r - r中的用户登录时间图
- typescript - React Navigation TypeScript:类型的参数......不可分配给“BottomTabNavigatorConfig”类型的参数
- curl - 使用外部 API 查找优化 BigQuery 表
- apache - .htaccess 重定向到除管理页面之外的另一个域
- css - 在 css 中有没有办法获取标签的内容?