首页 > 代码库 > 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.
1 public class Solution { 2 public int divide(int dividend, int divisor) { 3 if (dividend == 0) { 4 return 0; 5 } 6 7 long a=dividend,b=divisor; 8 boolean isNeg=false; 9 if (dividend < 0) {10 isNeg=!isNeg;11 a=-a;12 }13 if (divisor < 0) {14 isNeg = !isNeg;15 b = -b;16 }17 long i=0;18 if(b==1) {19 i=a; 20 }else21 {22 while (a >= b) {23 long temp = b;24 int k=1;25 while (temp + temp <= a) {26 k = k << 1;27 temp = temp + temp;28 }29 i = i | k;30 a = a - temp;31 } 32 }33 34 if (isNeg) {35 i = -i;36 }37 if (i > Integer.MAX_VALUE || i < Integer.MIN_VALUE) {38 return Integer.MAX_VALUE;39 } 40 return (int)i;41 }42 }
LeetCode Divide Two Integers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。