C實現除法
來源
Leetcode上的一個題,做完后感覺很有意義,因而記錄。
實際上自己也查閱了不少的實現除法的方式,最后還是感覺這個方法是最好的,沒有別的原因,就是快。
需要注意的一些點
- 正整數之間相互操作會顯得更加方便些,因此,我們需要考慮一些邊界問題。比如int的范圍是[-2e31,2e31-1],因此,如果-2e31轉化為正數時,就超出了int的范圍,最好的解決方式就是轉化為long long int。
- 當然也可以轉化為long int,這個取決於你的OS所定義的Long的范圍。
- 變成相反數的時候,選擇0-x會更加方便。
- ^異或符的使用也能幫助加快處理速度。
- 每個變量的type都需要斟酌過,因為很有可能會超過范圍。
代碼
int divide(int dividend, int divisor){
long long int y = (long long int)dividend;
long long int x = (long long int)divisor;
if(y < 0) y = 0 - y;
if(x < 0) x = 0 - x;
long long int tmp, one = 1, res = 0;
int restmp;
while(y >= x){
restmp = 0;
tmp = x;
while(y >= tmp){
tmp = tmp << 1;
restmp ++;
}
restmp --;
y -= (x << restmp);
res += (one << restmp);
}
if((dividend > 0)^(divisor > 0))
res = 0 - res;
if(res > 2147483647 || res < -2147483648)
res = 2147483647;
return res;
}