标签:
Divide two integers without using multiplication, division and mod operator.
比有趣在于1 提速过程 2怎么判断符号正负
public class Solution { public int divide(int dividend, int divisor) { long res =0, a = Math.abs((long) dividend), b=Math.abs((long) divisor), sum=0, pow = 0; if(b>a) return 0; // 中间加速环节相当于减去一个大b^pow, 然后剩下的部分再减去小的b^pow, ref: http://blog.csdn.net/perfect8886/article/details/23040143 while(a>=b){ sum=b; pow=1; while(a>=sum+sum){ sum += sum; pow += pow; } a -= sum; res += pow; } //return isNeg ? -res: res; res = (((dividend ^ divisor) >> 31) & 1)==1? -res:res; if(res>Integer.MAX_VALUE||res< Integer.MIN_VALUE) return Integer.MAX_VALUE; return (int) res; } }
标签:
原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4545377.html