Divide Two Integers
来源:互联网 发布:程序员必学课程 编辑:程序博客网 时间:2024/06/04 19:50
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
任何一个数字都可以表示为num=a_0*2^0+a_1*2^1+a_2*2^2+...+a_n*2^n,
因而可以用移位模拟出发,除数就是a_0+a_1+a_2...的和。
public class Solution { public static int divide(int dividend, int divisor) { if(divisor==0) return Integer.MAX_VALUE; if(divisor==-1 && dividend == Integer.MIN_VALUE) return Integer.MAX_VALUE; long pDividend = Math.abs((long)dividend); long pDivisor = Math.abs((long)divisor); int result = 0; while(pDividend>=pDivisor){ //calculate number of left shifts int numShift = 0; while(pDividend>=(pDivisor<<numShift)) numShift++; //dividend minus the largest shifted divisor result += 1<<(numShift-1); pDividend -= (pDivisor<<(numShift-1)); } if((dividend>0 && divisor>0) || (dividend<0 && divisor<0)) return result; else return -result; }}
0 0
- LeetCode: Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode: Divide Two Integers
- [LeetCode] Divide Two Integers
- Divide Two Integers
- Divide Two Integers
- LeetCode28:Divide Two Integers
- [Leetcode] Divide Two Integers
- LeetCode Divide Two Integers
- Divide Two Integers
- 【leetcode】Divide Two Integers
- Divide Two Integers
- Divide Two Integers
- [LeetCode]Divide Two Integers
- Divide Two Integers
- LeetCode-Divide Two Integers
- Divide Two Integers
- 25 - Divide Two Integers
- Linux下批量重命名文件bash命令详解
- 移动APP产品经理必学的工具和必上的酷站
- POJ 3270 Cow Sorting(置换环)
- 【暴力搜索】[UVa 11212]Editing a Book
- 收藏网站57
- Divide Two Integers
- source insight使用记录
- POJ3696 The Luckiest number 欧拉函数应用
- 收藏网站58
- NodeHTTP模块
- Trinitycore 物品,任务,生物 生成器
- android.view.ContextThemeWrapper cannot be cast to android.app.Activity
- 重置SQLSERVER表的自增列,让自增列重新计数
- hdu 1561 树形dp