Leetcode Divide, integers

Source: Internet
Author: User

Divide-integers without using multiplication, division and mod operator.

If It is overflow, return max_int.

Test instructions: Divide by two numbers without multiplication and mod calculations.

Idea: Because each number can be expressed as a binary, that is, num = a*2^0 + b*2^1 ...., so we just have to determine which 2^k can add results, the first way is the loop, the second is to find the maximum 2^k each time, the problem is to change 2 to B just

Class Solution {public:    int divide (int dividend, int divisor) {                long long a = ABS ((double) dividend);               Long Long B = ABS (double) divisor);        Long long res = 0;        while (a >= b) {            long long c = b;            for (int i = 0; a >= C; i++, C <<= 1) {                A-= C;                Res + = 1<<i;            }        }        int flag = ((divisor ^ dividend) >> 31)? -1:1;        if (RES * flag > Int_max)            return int_max;        else return res * flag;}    ;


Class Solution {public:    int divide (int dividend, int divisor) {        long long a = ABS ((double) dividend);               Long Long B = ABS (double) divisor);        Long long res = 0;        while (a >= b) {             long Long T = b, i = 1;             while ((T << 1) < a) {                 T <<= 1;                 I <<= 1;             }             A-= t;             res + = i;        }        int flag = ((divisor ^ dividend) >> 31)? -1:1;        if (RES * flag > Int_max)            return int_max;        else return res * flag;}    ;



Leetcode Divide, 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.