首页 > 代码库 > Leetcode-Divide Two Integers
Leetcode-Divide Two Integers
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Solution:
1 public class Solution { 2 public int divide(int dividend, int divisor) { 3 if (divisor==0) return Integer.MAX_VALUE; 4 if (dividend==0) return 0; 5 if (divisor==1) return dividend; 6 if (dividend==Integer.MIN_VALUE && divisor==-1) return Integer.MAX_VALUE; 7 8 boolean neg = false; 9 //change to all negtive number.10 if (dividend>0){11 dividend = -dividend;12 neg = !neg;13 }14 if (divisor>0){15 divisor = - divisor;16 neg = !neg;17 }18 19 int minDivisor = Integer.MIN_VALUE >> 1;20 int cur = divisor;21 int val = 1;22 while (cur>=minDivisor && cur>dividend){23 cur <<= 1;24 val <<= 1;25 }26 27 int res = 0;28 while (dividend<=divisor){29 while (cur<dividend){30 cur >>= 1;31 val >>= 1;32 }33 dividend -= cur;34 res += val;35 }36 37 if (neg) return -res;38 else return res;39 }40 }
Leetcode-Divide Two Integers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。