首页 > 代码库 > Divide Two Integers
Divide Two Integers
参考:http://www.cnblogs.com/springfor/p/3871008.html
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
这道看了网上的很多都是通过移位来做的,硬是没看懂
看了一下这个锅锅的,终于懂了
1 public class Solution { 2 public int divide(int dividend, int divisor) { 3 if(0 == dividend || 0 == divisor) 4 return 0; 5 boolean isNeg = ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) ? true : false; 6 long dividen_long = Math.abs((long)dividend); 7 long divisor_long = Math.abs((long)divisor); 8 if(divisor_long > dividen_long) 9 return 0;10 11 long sum = 0;12 long pow = 0;13 long result = 0;14 15 while(divisor_long <= dividen_long){16 sum = divisor_long;17 pow = 1;18 while(sum + sum <= dividen_long){19 sum += sum;20 pow += pow;21 }//while22 dividen_long -= sum;23 result += pow;24 }//while25 26 result = isNeg ? -result : result;27 if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)28 return Integer.MAX_VALUE;29 30 return (int)result;31 }32 }
Divide Two Integers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。