详细见:leetcode.com/problems/divide-two-integers
Java Solution: github
package leetcode;
public class P029_DivideTwoIntegers {
/*
* 这个方法会TLE
*/
static class Solution1 {
public int divide(int dividend, int divisor) {
if (divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1))
return Integer.MAX_VALUE;
if (Math.abs(divisor) == 1)
return divisor == 1 ? dividend : - dividend;
int ans = 0;
while (dividend >= divisor) {
dividend -= divisor;
ans ++;
}
return ans;
}
}
/*
* 正确的思路应该是:
* 使用类似二分的方法来计算
* 但是暴力右移是无法得到正确结果的。
* 1, dividend = 求和(i * 2 ^ k)
* 2, 一次一次地减去最大的2 ^ k就行了。
* 3 ms
* 10.48%
*/
static class Solution2 {
public int divide(int dividend, int divisor) {
if (divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1))
return Integer.MAX_VALUE;
boolean isNegative = (dividend ^ divisor) >>> 31 == 1;
int ans = (int)divide(Math.abs((long)dividend), Math.abs((long)divisor));
return isNegative ? - ans : ans;
}
public long divide(long n, long d) {
long ans = 0;
while (n >= d) {
int count = 1;
long val = d;
while (val + val < n) {
count = count + count;
val = val + val;
}
n -= val;
ans += count;
}
return ans;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/divide-two-integers/
16ms 48.96%
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
//for vc6 printf use I64d
#define LL __int64
int _d(LL a, LL b) {
int count = 0;
LL add1 = 0;
int ans = 0;
LL add = 0;
if (b == 1) return a;
while (add <= a) {
add1 = b;
count = 1;
while (add + add1 + add1 < a) {
add1 = add1 + add1;
count = count + count;
}
add += add1;
ans += count;
}
return ans - 1;
}
int divide(int a, int b) {
int sign = 0, ans = 0;
LL aa = a;
LL bb = b;
if (b == 0 || (a == INT_MIN && b == -1))
return INT_MAX;
sign = (a ^ b) >> 31;
aa = aa < 0 ? -aa : aa;
bb = bb < 0 ? -bb : bb;
//printf("%I64d\t%I64d\r\n", aa, bb);
return sign ? -_d(aa, bb) : _d(aa, bb);
}
int main() {
printf("%d\r\n", divide(34, 4));
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/divide-two-integers/
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月1日
@details: Solution: 62ms 47.40%
'''
from _testcapi import INT_MAX, INT_MIN
class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
#return divide by 0
if divisor == 0: return INT_MAX
#return INT_MIN / -1
if dividend == INT_MIN and divisor == -1:
return INT_MAX
sign = (dividend > 0) ^ (divisor > 0)
dividend, divisor = abs(dividend), abs(divisor)
if divisor == 1:
return -dividend if sign else dividend
ans, ans_add, val_add = 0, 1, divisor
while dividend >= 0:
ans_add, val_add = 1, divisor
while val_add + val_add < dividend:
val_add = val_add + val_add
ans_add = ans_add + ans_add
dividend -= val_add
ans += ans_add
ans -= 1
return -ans if sign else ans
if __name__ == "__main__":
print(Solution().divide(-5, 1))