Divide two integers without using multiplication, division and mod operator.
思路是使用人做除法时的运算式 每次取前除数长度或加1位还原成数字,做减法求出该位的商,需要注意很多特殊情况。。
class Solution { public: //a/b void Sub(string& a,string& b,string&ret,long long ib,stringstream& ss){ int i=0; string a1; bool all=false; bool end=false; if(a.length()<b.length()){ ret[0]='0'; ret.resize(1); return; } while(i<b.length()-1){ ret[i]='0'; i++; } while(a.length()>=b.length()){ bool big=true; for(int i=0;i<b.length();i++){ if(a[i]<b[i]){ big=false; break; } if(a[i]>b[i]){ break; } } if(!big){ if(a.length()==b.length()) { break; } a1=a.substr(0,b.length()+1); } else{ a1=a.substr(0,b.length()); } ss.clear(); ss<<a1; long long ia; ss>>ia; ss.clear(); int count=0; while(ia>=ib){ ia-=ib; count++; } int len=a1.length(); if(ia==0){ a1=""; if(all) for(int j=0;j<len-1;j++){ ret[i]='0'; i++; } all=true; } else{ all=false; ss<<ia; ss>>a1; ss.clear(); } ss.clear(); string a2=a.substr(len,a.length()-len); a1=a1+a2; if(a2=="")end=true; if(a1!=""){ ss<<a1; ss>>ia; ss.clear(); ss<<ia; ss>>a; } else a=a1; ret[i]=count+'0'; i++; } if(!end){ ret[i]='0'; i++; } ret.resize(i); } int divide(int dividend, int divisor) { // Note: The Solution object is instantiated only once and is reused by each test case. if(divisor==1)return dividend; if(divisor==-1)return -dividend; if(dividend==0)return 0; if(divisor==0){ if(dividend>0)return 2147493647; else return 0x80000000; } long long dvd=dividend,dvr=divisor; bool n1=false,n2=false; if(dvd<0){ dvd=-dvd; n1=true; } if(dvr<0){ dvr=-dvr; n2=true; } stringstream ss; string dd,dr; ss<<dvd; ss>>dd; ss.clear(); ss<<dvr; ss>>dr; ss.clear(); string result; result.resize(dd.length()); Sub(dd,dr,result,dvr,ss); ss.clear(); ss<<result; long long ret; ss>>ret; if(n1==n2){ return (int)ret; } else{ int ret2=-ret; return ret2; } } };