您的位置:首页 > 其它

LeetCode 29. Divide Two Integers(整数除法)

2018-03-19 15:47 405 查看
题目描述:
    Divide two integers without using multiplication, division and mod operator.
    If it is overflow, return MAX_INT.
分析:
    题意:给定两个整型数,求它们的商并返回(不能使用乘法、除法、取模运算符号,结果溢出则返回MAX_INT)
    思路:由于各种运算符的限制使用,我们考虑使用位运算来解决(因为位运算可以模拟出加法、减法、乘法、除法的运算过程)。为了方便判断溢出,我们先把两个数转化为长整型数(long long int)m、n,同时判断除法得到结果的正负号(并取得m、n的绝对值)。我们找到一个最大的指数exp,使得m大于等于(n << exp),那么(1  << exp)可以作为结果加入答案中,然后用m减去(n << exp)更新被除数,重复该过程模拟除法运算。最终返回答案。

代码:
#include <bits/stdc++.h>

using namespace std;

#define LL long long

// bit manipulation
class Solution {
public:
int divide(int dividend, int divisor) {
LL m = (LL) dividend;
LL n = (LL) divisor;
// Exceptional Case:
if(m == 0){
return 0;
}
if(n == 0){
return INT_MAX;
}
bool sign = false;
// sign
if(m < 0){
sign = !sign;
m = -m;
}
if(n < 0){
sign = !sign;
n = -n;
}
if(m < n){
return 0;
}
// get answer
LL ans = 0;
// not the condition: while(m > 0)
while(m >= n){
int exp = 0;
while(m >= (n << (exp + 1))){
exp++;
}
// ans += (LL)(1 << exp); will cause an error!
ans += ((LL)1 << exp);
m -= (n << exp);
}
if(sign){
ans = -ans;
}
// check overflow
if(ans > INT_MAX || ans < INT_MIN){
ans = (LL)INT_MAX;
}
return (int)ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息