首页 > 代码库 > 62. Divide Two Integers
62. Divide Two Integers
Divide Two Integers
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; }};
62. Divide Two Integers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。