Divide two integers without using multiplication, division and mod operator.
Analysis: it is easy to understand the meaning of a question, that is, division is done without multiplication and division and modulo calculation. It is easy to think of a method that is always used for subtraction, then counting, and timeout. Find a solution on the Internet and use bitwise operations, which means that any integer can be expressed as a linear combination of groups based on the power of 2, that is, num = a_0 * 2 ^ 0 + a_1 * 2 ^ 1 + A_2 * 2 ^ 2 +... + a_n * 2 ^ n. Based on the above formula and the shift left is equal to multiply by 2, we first let the divisor shift left until it is greater than the divisor to get a maximum base N value, indicating that the divisor contains at least 2 ^ n divisor, then subtract the base number, and find n-1 ,..., the value of 1. The result is obtained by adding all the base numbers. The Code is as follows:
Class solution {public: int divide (INT dividend, int divisor) {int res = 0; int flag = 1; if (dividend <0 & divisor> 0) | (dividend> 0 & divisor <0) Flag =-1; long d = ABS (long) dividend ); // Why can only long s = ABS (long) divisor); While (S <= d) {int CNT = 1; long TMP = s; // only long can be TMP <= 1; while (TMP <= d) {CNT <= 1; TMP <= 1;} res + = CNT; d-= (TMP >>= 1);} return (INT) flag * res ;}};
Clever, learn to use bitwise operations. Also use long
Leetcode 28th -- divide two integers