您的位置:首页 > 其它

LeetCode: Divide Two Integers

2012-11-29 12:20 344 查看
Divide two integers without using multiplication, division and mod operator.

睡眠不够,脑子明显不好使了,明天得补补觉了。

class Solution {
public:
int divide(int dividend, int divisor) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int count = 0;
int offset = 0;
long long  num = abs((long long)dividend);
long long n_divisor = abs((long long)divisor);
while(num >= n_divisor){
n_divisor <<= 1;
offset++;
}
while(offset >= 0){
while(num >= n_divisor)
{
count += 1 << offset;
num -= n_divisor;
}
n_divisor>>=1;
offset--;
}
if(!isSame(dividend, divisor))
{
count = 0 - count;
}
return count;
}
bool isSame(int a, int b){
if(a >= 0 && b >= 0){return true;}
if(a < 0 && b < 0){return true;}
return false;
}
};


今天写的

class Solution {
public:
int divide(int dividend, int divisor) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int offset = 0;
long long temp = abs((long long)divisor);
bool is_neg = false;
if((dividend>> 31 & 1) ^ (divisor>>31 & 1))
is_neg = true;
long long dvd = abs((long long)dividend);
while(temp <= dvd){
temp<<=1;
++offset;
}
int count = 0;

while(offset > -1){
while(dvd >= temp){
dvd -= temp;
count += 1<<offset;
}
temp>>=1;
offset--;
}
if(is_neg) return 0 - count;
return count;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: