LeetCode -- Divide Two Integers
来源:互联网 发布:侠盗飞车3罪恶都市mac 编辑:程序博客网 时间:2024/05/01 02:37
Divide Two Integers
题目描述
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
整除两个整数,不能使用乘除,取模。
思路:
题目考的是位运算,求出除数的最大位移数max,使用被除数-1<<max,使用剩余的数继续计算。
注意特殊值的情况。
题目描述
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
整除两个整数,不能使用乘除,取模。
思路:
题目考的是位运算,求出除数的最大位移数max,使用被除数-1<<max,使用剩余的数继续计算。
注意特殊值的情况。
public class Solution { public int Divide(int dividend, int divisor) { if(dividend == 0){ return 0; } if(divisor == 0){ return dividend > 0 ? int.MaxValue : int.MinValue; } long x1 = dividend; long x2 = divisor; var negtive = false; if(x1 < 0){ x1 = -x1; negtive = !negtive; } if(x2 < 0){ x2 = -x2; negtive = !negtive; } long result = 0; long remain = x1; while(remain >= x2) { var shifts = S(remain, x2); remain -= x2 << shifts; var v = 1<< shifts; result += v; //Console.WriteLine(remain + ","+ v); } if(negtive){ result = -result; } if(result < 0 && (result + int.MaxValue < 0)) //// less than int.MinValue { return int.MaxValue; } return (int)result; } private int S(long x, long y){ int count = -1; while(x >= y){ x>>=1; count ++; } return count; }}
1 0
- LeetCode: Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode: Divide Two Integers
- [LeetCode] Divide Two Integers
- [Leetcode] Divide Two Integers
- LeetCode Divide Two Integers
- 【leetcode】Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode-Divide Two Integers
- LeetCode: Divide Two Integers
- Divide Two Integers - leetcode
- Leetcode: Divide Two Integers
- LeetCode:Divide Two Integers
- leetcode Divide Two Integers
- LeetCode Divide Two Integers
- LeetCode | Divide Two Integers
- Leetcode: Divide Two Integers
- Divide Two Integers -- LeetCode
- LeetCode -- Ransom Note
- Linux下的C语言编程——进程间通过signal函数通信简单操作
- java中类方法与对象方法区别
- Dynamic ODT
- 竖式问题--c
- LeetCode -- Divide Two Integers
- javaScript创建对象
- matlab PCA-SVD简单地实现特征脸方法(Eigenface)
- java.lang.UnsupportedClassVersionError的产生原因和解决办法深度剖析
- C++栈和队列
- 使用Octave音频处理(三):数学技术处理音频文件
- android用JSONObject和JSONArray解析json格式数据
- 转
- 最短路径四大算法核心Code