Divide two integers without using multiplication, division and mod operator.
用 unsigned int 可以解决溢出问题
class Solution {
public:
int divide(int dividend, int divisor) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
unsigned int absDivident = dividend>=0?dividend:-dividend;
unsigned int absDivisor = divisor>=0?divisor:-divisor;
vector<unsigned int> value;
bool sign = true; //true for positive, false for negative
if((dividend>0&&divisor<0) || (dividend<0&&divisor>0))
{
sign = false;
}
int count = 0;
unsigned int moveDivisor = absDivisor;
unsigned int answer = 0;
while(moveDivisor>0 && moveDivisor<=absDivident)
{
count ++;
value.push_back(moveDivisor);
moveDivisor = moveDivisor<<1;
}
if(count==0) return 0;
count --;
while(count>=0 && absDivident!=0)
{
if(absDivident>=value[count])
{
answer += 1<<count;// 或者 answer = answer + (unsigned int)(1<<count); 一定要强制转换成无符号数
absDivident = absDivident-value[count];
}
count--;
}
return sign?answer:-answer;
}
};