[LeetCode]Divide Two Integer

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

思考:位运算。AC的时候真的想说一句“尼玛。。“,用unsigned int 超时,莫名其妙,折腾到半夜,百度一下改为long long过了。。我也不明白到底怎么回事,毕竟不是CS出身,哎。。太晚了,明天再看。

VC不支持long long,珍爱生命,远离VC。

class Solution {
public:
    int divide(int dividend, int divisor) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        assert(divisor!=0);
		if(dividend==0) return 0;
		bool flag=true;
		if((dividend>0&&divisor<0)||(dividend<0&&divisor>0)) flag=false;
		long long c=dividend;
		long long d=divisor;
		long long a=abs(c);
		long long b=abs(d);
	    long long ret=0;
		long long count=1;
		while(a!=0)
		{
			b=abs(d);
			if(a<b) 
			{
				a=0;
				count=0;
				break;
			}
			count=1;
			while(b<a)
			{
				b<<=1;
				count<<=1;
			}	
			if(b!=a)
			{
				b>>=1;
				count>>=1;
			}
			a-=b;
			ret+=count;
		}
		return (flag)?ret:-ret;
    }
};

  

posted @ 2013-11-25 01:49  七年之后  阅读(386)  评论(0编辑  收藏  举报