Leetcode: Divide Two Integers

Divide two integers without using multiplication, division and mod operator.

用减法:Time Limit Exceeded

 

int divide(int dividend, int divisor) {

        // Note: The Solution object is instantiated only once.

        int res = 0;

		if(divisor == 0) return 0;

		if(divisor==1)return dividend;

		else if(divisor == -1)return -dividend;



		bool ispositive = true;

		if(dividend<0)

		{

			dividend = -dividend;

			if(divisor<0)

				divisor = -divisor;

			else

				ispositive = false;

		}

		else if(divisor<0)

		{

			divisor = -divisor;

			ispositive = false;

		}

		while(dividend>=divisor)

		{

		    dividend -= divisor;

			res++;

		}

		if(!ispositive)

			res = -res;

		return res;

    }


 

减法+位操作:Accepted

 

int divide(int dividend, int divisor) {

        // Note: The Solution object is instantiated only once.

        long long a = abs((double)dividend);

		long long b = abs((double)divisor);

		long long res = 0;

		while(a >= b)

		{

			long long c = b;

			for(int i = 0; a >= c; i++, c <<=1)

			{

				a -= c;

				res += 1<<i;

			}

		}

		return ((dividend ^ divisor) >> 31) ? (-res) : (res);

    }


 



 

你可能感兴趣的:(LeetCode)