Leetcode29dividetwointegers--in Java__leetcode

Source: Internet
Author: User
Tags abs

The main approach is: the first constant through the shift operation to find divisor closest to the dividend multiples, such as dividend is 100, the divisor is 3, this multiple is 32.

Then use 100 minus 3 of 32 times times, where 32 times times is generated by the left shift, and no multiplication is used.

At this point, then use a loop to find 3 times the most close to 100 and its 32 times times the difference, that is, find the nearest to 4 of the multiple, through the constant temptation of 16 times times, 8 times times, 4 times times ... (moving right), the result is 1 time times, 3.

Repeat the bad action, to find the nearest 1 of the 3 multiples, of course, 0 times times. Finally, when the value of the difference is less than one times 3, the loop exits.

In order to solve the overflow problem, we refer to the Http://www.cnblogs.com/ganganloveu/p/4174062.html method, use long to do the operation, and finally decide not to overflow and then convert to int.

public int divide (int dividend, int divisor) {
		long m = dividend;
		Long n = divisor;
		Long ABSN = Math.Abs (n);
		if (divisor==0) {return
			integer.max_value;
		}
		if (dividend==0) {return
			0;
		}
		
		Boolean Flag1 = dividend<0?true:false;
		Boolean flag2 = divisor<0?true:false;
		m = Math.Abs (m);
		n = Math.Abs (n);
		if (m<n) return
			0;
		Long ct = 1;//current multiple
		long tempresult = 0;
		while ((n<<1) <=m) {
			n = n<<1;
			ct = ct<<1;
		}
		
		while (true) {
			Tempresult = tempresult + ct;
			
			m = m-n;
			n = n>>1;
			ct = ct>>1;
			
			while (m<n) {
				n = n>>1;
				ct = ct>>1;
			}
			if (N<ABSN) break
				;
		
		if ((flag1==true&&flag2==false) | | (flag1==false&&flag2==true))
			return-(int) tempresult;
		if (tempresult>integer.max_value) return
			integer.max_value;
		return (int) tempresult;
    }


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.