Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
public class Solution { public int divide(int dividend, int divisor) { long a,b,flag=0,sum=0; long[] map=new long[33],times=new long[33]; if(dividend<0 && divisor<0)flag=1; else if(dividend>0 && divisor>0)flag=1; a=Math.abs((long)dividend); b=Math.abs((long)divisor); int i=0; map[0]=b;times[0]=1; while(map[i]<=a){ i++; map[i]=map[i-1]+map[i-1]; times[i]=times[i-1]+times[i-1]; } for(int j=i-1;j>=0;j--){ while(a >= map[j]){ a-=map[j]; sum+=times[j]; } } sum=flag==1?sum:-sum; if(sum>Integer.MAX_VALUE || sum<Integer.MIN_VALUE)return Integer.MAX_VALUE; return (int)sum; } }
long long ABS(long long a){ return a>0?a:-a; } int divide(int dividend, int divisor) { int i=0,j,flag=0; long long sum=0,a,b,map[33],times[33],STOP=1; STOP=((long long)2147483647)+1; if(divisor==0)return INT_MAX; if(dividend==0)return 0; if((dividend>0 && divisor>0) || (dividend<0 && divisor<0))flag=1; a=ABS((long long)dividend); b=ABS((long long)divisor); map[0]=b;times[0]=1; while(map[i] <= a && i<33){ i++; map[i]=map[i-1]+map[i-1]; times[i]=times[i-1]+times[i-1]; } for(j=i-1;j>=0;j--){ while(a >= map[j]){ a-=map[j]; sum+=times[j]; } } sum=flag?sum:-sum; if(sum<INT_MIN || sum > INT_MAX)return INT_MAX; return (int)sum; }
class Solution { public: int divide(int dividend, int divisor) { int i=0,j,flag=0; long long sum=0,a,b,map[33],times[33],STOP=1; STOP=STOP<<31; if(divisor==0)return INT_MAX; if((dividend>0 && divisor>0) || (dividend<0 && divisor<0))flag=1; a=abs((long long)dividend); b=abs((long long)divisor); map[0]=b;times[0]=1; while(map[i] <= STOP){ i++; map[i]=map[i-1]+map[i-1]; times[i]=times[i-1]+times[i-1]; } for(j=i-1;j>=0;j--){ while(a >= map[j]){ a-=map[j]; sum+=times[j]; } } sum=flag?sum:-sum; if(sum<INT_MIN || sum > INT_MAX)return INT_MAX; return (int)sum; } };
class Solution: # @param {integer} dividend # @param {integer} divisor # @return {integer} def divide(self, dividend, divisor): flag=0 if dividend>0 and divisor>0:flag=1 elif dividend<0 and divisor<0:flag=1 if dividend==0:return 0 dividend=abs(dividend) divisor=abs(divisor) map=[0 for i in range(33)] times=[1 for i in range(33)] i=0 map[0]=divisor;times[0]=1 while map[i]<=dividend: i+=1 map[i]=map[i-1]+map[i-1] times[i]=times[i-1]+times[i-1] j=i-1;sum=0 while j>=0: while map[j]<=dividend: dividend-=map[j] sum+=times[j] j-=1 sum = -sum if flag==0 else sum if sum>2147483647:return 2147483647 return sum
LeetCode 29 Divide Two Integers (C,C++,Java,Python)
原文地址:http://blog.csdn.net/runningtortoises/article/details/45688813