标签:style blog http io ar div 问题 sp log
Divide two integers without using multiplication, division and mod operator.
思路: 类同 趣味算法之数学问题:题4.
两点需要注意: 1. 除数或被除数为最大负数时,转化为正数会溢出。2. divisor + divisor 可能会溢出。
class Solution { public: int divide(int dividend, int divisor) { if(divisor == 0) return INT_MAX; bool signal = false; bool overflow = false; if(dividend < 0) { signal = !signal; if(dividend == INT_MIN) { overflow = true; dividend++; } dividend *= -1; } if(divisor < 0) { signal = !signal; if(divisor == INT_MIN) { if(overflow) return 1; else return 0; } divisor *= -1; } int result = 0; while(dividend >= divisor) { int x(divisor); int r(1); while(dividend-x >= x) { x += x; r += r; } dividend -= x; result += r; } if(overflow && dividend +1 == divisor) result++; return signal ? (-result) : result; } };
标签:style blog http io ar div 问题 sp log
原文地址:http://www.cnblogs.com/liyangguang1988/p/3961196.html