题目:两整数相除

难度:Medium

题目内容

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero.

翻译

给定两个整数,被除数和除数,不使用乘法,除法和mod运算符。

在除以除数后,返回商数。

整数除法应该截断为零。

Example 1:

Input: dividend = 10, divisor = 3
Output: 3

Example 2:

Input: dividend = 7, divisor = -3
Output: -2

我的思路:因为此题需要考虑的边界情况太多,而重点考察的却不是这些,故只做算法分析,不求跑通所有代码。

    最笨的方法:直接循环减去除数。。。

    方法二:之前印象中好像在哪见过,每次循环都减去能减的最大的除数*2^n,并且每次循环把2次幂都加起来。商就是这些2次幂的和。

举个例子:20/3,

  第一次循环,20>3*1,20>3*2,20>3*2*2,已经最大,打住, dividend=20-3*2*2=8, ans = 2*2 = 4

  第二次循环,8>3*1,8>3*2,已经最大,打住, dividend=8-3*2=2, ans = 4 + 2 = 6

  dividend < 3 退出循环,最后 ans = 6

MyCode

     public int divide(int dividend, int divisor) {
if (dividend != 0 && dividend == -dividend && divisor == -1) {
return -(dividend+1);
}
return div(dividend, divisor);
}
public static int div(int x, int y) {
int tag = 1;
if ((x ^ y) < 0) { // 位运算符优先级很低,记得加括号
tag = -1;
if (x < 0) {
x = -x;
} else {
y = -y;
}
} else if (x < 0) {
x = -x;
y = -y;
} // 都设置成正整数
int ans = 0;
while (x >= y) {
int flag = 1;
while ((x >> 1) >= y * flag) { // 如果使用x >= y * (flag << 1) 则有可能溢出
flag <<= 1;
}
x -= y*flag;
ans += flag;
}
return ans*tag;
}

编码过程中出现问题

1、bad operand types for binary operator “^”

  ————位运算符的优先级很低,甚至比==都要低,所以遇见位运算符要记得加括号。

2、溢出

  ————在23行处,进行了>>1(乘以2)的判断运算,此时可能溢出,所以在进行判断运算时,即先运算再判断是否能如此运算的时候,应该将判断符(==、>=等)两边的运算符平衡一下,如果一边可能溢出,则将此运算符移至另一边。【此处与之前的leetCode的某一题貌似是 数字反转 很像】

答案代码

    public int divide(int dividend, int divisor) {
if(dividend<<1 == 0 && divisor == -1){// x /y = -2^32 / -1, overflow
return (-1) >>> 1;
} if(divisor == 1 || dividend == 0){ // x / y = x / 1 or 0 / y
return dividend;
}
if(divisor == dividend) return 1; // x / y when x == y
else if(divisor<<1 == 0) return 0; // x / y = x / (-2^32) int sign; //sign
if(divisor < 0 && dividend < 0 || divisor > 0 && dividend > 0){
sign = 1;
}else{
sign = -1;
} divisor = divisor < 0 ? -divisor : divisor; // positive divisor
int left = dividend, res = 0;
if(dividend << 1 == 0){ // if x / y = (-2^32) / y, first we add x by y, then -x will not overflow
left += divisor;
res++;
}
left = left > 0 ? left : -left; int tDivisor = divisor, tA = 1;
while(left >= divisor){
tDivisor = divisor;
tA = 1;
while(tDivisor << 1 > 0 && left >= tDivisor << 1){ // max tDivisor = tA * divisor <= left
tDivisor <<= 1;
tA <<= 1;
}
res += tA;
left -= tDivisor;
}
return sign == 1 ? res : -res;
}

其实真正的代码从27行开始,和我代码是一个意思,不过前面多出了很多处理边界的情况,在此不做讨论。

另外一种方法——二分法

和朋友讨论发现另外一种巧妙地解法,用二分法:

     public static int div2(int x, int y) {
int tag = 1;
if ((x ^ y) < 0) { // 位运算符优先级很低,记得加括号
tag = -1;
if (x < 0) {
x = -x;
} else {
y = -y;
}
} else if (x < 0) {
x = -x;
y = -y;
}
int ans = 0; // 算法从此处开始
int low = 1;
int high = x;
while (low <= high) {
int mid = low + ((high-low)>>1);
int rest = x - y*mid;
System.out.println(rest);
if (rest >= 0 && rest < y) {
ans = mid;
break;
}
if (rest < 0) {
high = mid - 1;
} else if (rest >= y) {
low = mid + 1;
}
}
return ans * tag;
}

LeetCode第[29]题(Java):Divide Two Integers的更多相关文章

  1. 【LeetCode每天一题】Divide Two Integers(两整数相除)

    Given two integers dividend and divisor, divide two integers without using multiplication, division ...

  2. LeetCode第[18]题(Java):4Sum 标签:Array

    题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + ...

  3. LeetCode第[1]题(Java):Two Sum 标签:Array

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  4. LeetCode第[46]题(Java):Permutations(求所有全排列) 含扩展——第[47]题Permutations 2

    题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...

  5. LeetCode第[1]题(Java):Two Sum (俩数和为目标数的下标)——EASY

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  6. 【Leetcode】【Medium】Divide Two Integers

    Divide two integers without using multiplication, division and mod operator. If it is overflow, retu ...

  7. leetcode-【中等题】Divide Two Integers

    题目 Divide two integers without using multiplication, division and mod operator. If it is overflow, r ...

  8. LeetCode第[4]题(Java):Median of Two Sorted Arrays 标签:Array

    题目难度:hard There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median ...

  9. LeetCode第[4]题(Java):Median of Two Sorted Arrays (俩已排序数组求中位数)——HARD

    题目难度:hard There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median ...

随机推荐

  1. 微信支付 php发送POST请求

    https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=20_1 <_xml> <mch_id>132</mc ...

  2. WSGI基础知识(转)

    add by zhj: WSGI全称Web Server Gateway Interface,即Web网关接口.其实它并不是OSI七层协议中的协议,它就是一个接口(即函数)而已,而WSGI规定了该接口 ...

  3. 我的Android进阶之旅------>Android Studio 快捷键整理分享

    正式转战Android Studio了,首先把Android Studio的快捷键摘录下来,以备后用. (官网的快捷键列表如下  https://developer.android.com/studi ...

  4. use html5 video tag with MSE for h264 live streaming

    本编博客记录桌面虚拟化移动端预研. 完整demo: https://github.com/MarkRepo/wfs.js 常见的直播方案有RTMP RTSP HLS 等等, 由于这些流都需要先传输到服 ...

  5. 解决 hybird 应用中重复获取 WebView,导致页面元素无法识别的问题

    转载地址:http://blog.csdn.net/testman930/article/details/50799532 问题描述 在测APP的业务流,WebView和Native模式耦合在一起.例 ...

  6. Linux基础——系统监控

    系统监视和进程控制工具——top(任务管理器) top命令是Linux下常用的性能分析工具,能够实时显示系统中各个进程的资源占用状况,类似于Windows的任务管理器. 各行数据大致解释如下: 12: ...

  7. 关于OAuth的state参数的作用

    引用: https://blog.csdn.net/gjb724332682/article/details/54428808 在开发 OAuth认证服务器 的时候,开发者的安全意识不高的话,很可能会 ...

  8. springmvc 原生servlet支持

    /** * 可以使用 Serlvet 原生的 API 作为目标方法的参数 具体支持以下类型 * * HttpServletRequest * HttpServletResponse * HttpSes ...

  9. HDU 4370 - 0 or 1 (SPFA+思维)

    题意:给一个N*N的矩阵C,和一个N*N的只由0和1组成的矩阵X. X满足以下条件: 1.X 12+X 13+...X 1n=1  2.X 1n+X 2n+...X n-1n=1  3.任意 i (1 ...

  10. java synchronized和(ReentrantLock)区别

    原文:http://blog.csdn.net/zheng548/article/details/54426947 区别一:API层面 syschronized使用 synchronized即可修饰方 ...