Leetcode 28th -- divide two integers

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.