Leetcode|Divide Two Integers

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mike_learns_to_rock/article/details/46778029

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

If it is overflow, return MAX_INT.

位操作,详见我的另一篇讲解位操作的博文。
此题在leetcode的通过率只有15%,主要是溢出的问题需要好好考虑。

int divide(int x,int y){
   assert(y!=0);
   bool neg=(x<0)^(y<0);
   unsigned int x1=x>0?x:-x;
   unsigned int y1=y>0?y:-y;
   long long pos=y1;
   unsigned int res=0;
   int bit=0;
   for(;pos<=x1;bit++)
   {
       pos=pos<<1;
   }
   //if(x1>INT_MAX) return bit;
   while(x1>=y1){
     if(x1>=pos){
        res|=1<<bit;
        x1-=pos;
     }else{
         pos>>=1;
         bit--;
     }
   }

   if(res>INT_MAX&&!neg) return INT_MAX;
   if(neg) res=-res;
   return (int)res;
}

猜你喜欢

转载自blog.csdn.net/mike_learns_to_rock/article/details/46778029