solution.cpp 659 字节
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
	int divide(int dividend, int divisor)
	{
		int signal = 1;
		unsigned int dvd = dividend;
		if (dividend < 0)
		{
			signal *= -1;
			dvd = ~dvd + 1;
		}
		unsigned int dvs = divisor;
		if (divisor < 0)
		{
			signal *= -1;
			dvs = ~dvs + 1;
		}
		int shift = 0;
		while (dvd > dvs << shift)
		{
			shift++;
		}
		unsigned int res = 0;
		while (dvd >= dvs)
		{
			while (dvd < dvs << shift)
			{
				shift--;
			}
			res |= (unsigned int)1 << shift;
			dvd -= dvs << shift;
		}
		if (signal == 1 && res >= INT_MAX)
		{
			return INT_MAX;
		}
		else
		{
			return res * signal;
		}
	}
};