Fetching contributors…
Cannot retrieve contributors at this time
executable file 100 lines (86 sloc) 2.63 KB
title date categories tags
LeetCode刷题笔记-029DivideTwoIntegers
2018-05-03 02:00:37 -0700

 LeetCode

```package net.jerryfu.leetCodeMedium;

import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class _024SwapNodesInPairs {

public class _029DivideTwoIntegers {

public int divide(int dividend, int divisor) {
if (divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1)) {
return Integer.MAX_VALUE;
}
if (divisor==1) {
return dividend;
}
int dd = Math.abs(dividend);
int ds = Math.abs(divisor);
int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;
int result = 0;
while (dd >= ds) {
int temp = ds, times = 1;
while (dd > (temp << 1)) {
times <<= 1;
temp <<= 1;
}
result += times;
dd -= temp;
}
return sign > 0 ? result : -result;
}

@Test
public void test() {
assertEquals(3, divide(10, 3));
assertEquals(3, divide(29, 8));
assertEquals(-2, divide(7, -3));
assertEquals(4, divide(8, 2));
assertEquals(0, divide(2, 8));
assertEquals(1, divide(2, 2));
assertEquals(2147483647, divide(2147483647, 1));
}
}
```

```class Solution {
public:
int divide(int dividend, int divisor) {
long long m = abs((long long)dividend), n = abs((long long)divisor), res = 0;
if (m < n) return 0;
while (m >= n) {
long long t = n, p = 1;
while (m > (t << 1)) {
t <<= 1;
p <<= 1;
}
res += p;
m -= t;
}
if ((dividend < 0) ^ (divisor < 0)) res = -res;
return res > INT_MAX ? INT_MAX : res;
}
};```
You can’t perform that action at this time.