Leetcode|Divide Two Integers

来源:互联网 发布:如何下载windows 10 编辑:程序博客网 时间:2024/06/06 04:26

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;}
0 0
原创粉丝点击