[LeetCode] 29. Divide Two Integers, leetcode29.divide
[Question]
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
[Analysis]
Multiplication, division, and modulo operations are not supported.
The simplest method is to constantly subtract the divisor. The number of iterations of this method is the result size. For example, if the result is n, the algorithm complexity is O (n ). However, this will time out.
[Code]
/********************************** Date: * Author: SJF0115 * Subject: 29. divide Two Integers * URL: https://oj.leetcode.com/problems/divide-two-integers/* result: AC * Source: Time Limit Exceeded * blog: * *********************************/# include <iostream> using namespace std; class Solution {public: int divide (int dividend, int divisor) {// when dividend = INt_MAX,-dividend overflows. Use long a = dividend> = 0? Dividend:-(long) dividend; // when divisor = INt_MAX, use long B = divisor> = 0? Divisor:-(long) divisor; int count = 0; // continuously decreases while (a> = B) {a-= B; count ++ ;} // while // Positive and Negative int isPositive = (dividend ^ divisor)> 31; if (isPositive = 0) {return count ;}// if else {return-count ;} // else }}; int main () {Solution solution; int dividend =-2147483648; int divisor =-1; int result = solution. divide (dividend, divisor); // output cout <result <endl; return 0 ;}
[Analysis 2]
Through the above timeout example, we can summarize some things and make some optimizations.
The bitwise operation doubles the divisor each time to accelerate the process.
Code 2]
/********************************** Date: * Author: SJF0115 * Subject: 29. divide Two Integers * URL: https://oj.leetcode.com/problems/divide-two-integers/* result: AC * Source: Time Limit Exceeded * blog: * *********************************/# include <iostream> # include <climits> using namespace std; class Solution {public: int divide (int dividend, int divisor) {// when dividend = INt_MAX,-dividend will overflow and use long a = di Vidend> = 0? Dividend:-(long) dividend; // when divisor = INt_MAX,-divisor overflows. Use long B = divisor> = 0? Divisor:-(long) divisor; long result = 0; // continuously decreases while (a> = B) {long c = B; for (int I = 0; a> = c; ++ I, c <= 1) {a-= c; result + = 1 <I ;} // for} // while // positive and negative if (dividend> 0 & divisor <0) | (dividend <0 & divisor> 0 )) {result =-result;} // if // If it is overflow, return MAX_INT. if (result> INT_MAX | result <INT_MIN) {result = INT_MAX;} return static_cast <int> (result) ;}}; int main () {Solution; int dividend =-2147483648; int divisor =-1; int result = solution. divide (dividend, divisor); // output cout <result <endl; return 0 ;}
Ignore a previous detail: If it is overflow, return MAX_INT.
2147483648 overflow, so MAX_INT 2147483647 is returned.