[Leetcode] divide two integers

Source: Internet
Author: User

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

Https://oj.leetcode.com/problems/divide-two-integers/

Train of Thought 1: we can only use subtraction, minus divisor and Tots in sequence, and it definitely times out.

Idea 2: each time minus n times the divisor, the result is also added n times, so we need to increase the divisor by N times.

  1. Extend int to long to prevent overflow.
  2. Multi [I] stores the case where the divisor is increased by I times and then subtracted by the divisor.
  3. Negative number processing.
public class Solution {    public int divide(int dividend, int divisor) {        if (dividend == 0 || divisor == 1)            return dividend;        long divid = dividend;        long divis = divisor;        boolean neg = false;        int result = 0;        if (dividend < 0) {            neg = !neg;            divid = -divid;        }        if (divisor < 0) {            neg = !neg;            divis = -divis;        }        long[] multi = new long[32];        for (int i = 0; i < 32; i++)            multi[i] = divis << i;        for (int i = 31; i >= 0; i--) {            if (divid >= multi[i]) {                result += 1 << i;                divid -= multi[i];            }        }        return (neg ? -1 : 1) * result;    }    public static void main(String[] args) {        System.out.println(new Solution().divide(5, 2));        System.out.println(new Solution().divide(5, -2));        System.out.println(new Solution().divide(100, 2));        System.out.println(new Solution().divide(222222222, 2));        System.out.println(new Solution().divide(-2147483648, 2));    }}

 

 

Refer:

Http://blog.csdn.net/doc_sgl/article/details/12841741

Http://blog.csdn.net/linhuanmars/article/details/20024907

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.