class Solution { public: int divide(int dividend, int divisor) { if(dividend==0x80000000&&divisor==-1)//溢出情况 return 0x7FFFFFFF; long cur_dividend=dividend;//用long吧,不然太难搞了 long cur_divisor=divisor; bool flag=false;//记录符号 if(dividend<0) { cur_dividend=~cur_dividend+1;//取反加一,将补码弄成原码 flag=!flag; } if(divisor<0) { cur_divisor=~cur_divisor+1; flag=!flag; } long res=0; long temp=cur_divisor; while(cur_dividend-temp>=0)//就不停检查当前最多容纳的cur_divisor { int cur_res=1; while((temp<<1)<cur_dividend)//不停*2,对速度特别友好 { temp=temp<<1; cur_res=cur_res<<1; } cur_dividend=cur_dividend-temp;//,如果容纳不了,减去已经容纳的,然后继续检测 temp=cur_divisor; res+=cur_res; } if(flag) res=~res+1; return res; } };
分析:
真的是,够够的,一开始想对被除数一半一半展开,但是对于奇偶情况特别复杂,于是想到这个,但是这个我又对取值范围难以掌控,最后用了long类型,唉,好麻烦啊这个题。