Java divide two integers

LeetCode – Divide Two Integers (Java)

Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT.

This problem can be solved based on the fact that any number can be converted to the format of the following:

The time complexity is O(logn).

Java Solution

public int divide(int dividend, int divisor) { //handle special cases if(divisor==0) return Integer.MAX_VALUE; if(divisor==-1 && dividend == Integer.MIN_VALUE) return Integer.MAX_VALUE; //get positive values long pDividend = Math.abs((long)dividend); long pDivisor = Math.abs((long)divisor); int result = 0; while(pDividend>=pDivisor){ //calculate number of left shifts int numShift = 0; while(pDividend>=(pDivisornumShift)){ numShift++; } //dividend minus the largest shifted divisor result += 1(numShift-1); pDividend -= (pDivisor(numShift-1)); } if((dividend>0 && divisor>0) || (dividend0 && divisor0)){ return result; }else{ return -result; } }

If you want someone to read your code, please put the code inside

 and 

tags. For example:

Источник

How to Do Division in Java (Integer and Floating Point)

This article was co-authored by wikiHow staff writer, Nicole Levine, MFA. Nicole Levine is a Technology Writer and Editor for wikiHow. She has more than 20 years of experience creating technical documentation and leading support teams at major web hosting and software companies. Nicole also holds an MFA in Creative Writing from Portland State University and teaches composition, fiction-writing, and zine-making at various institutions.

This article has been viewed 62,097 times.

There are two types of division in Java—integer division and floating-point division. Both types use the forward slash (/) symbol as the operator, following the format dividend / divisor. Read on to learn how to divide two integers (non-decimal whole numbers) to receive an integer quotient, and how to use floating point division to get a decimal result.

Integer Division

Image titled 12966108 1

When you divide two integers in Java, the fractional part (the remainder) is thrown away. For example, if you were to divide 7 by 3 on paper, you’d get 2 with a remainder of 1. But when you divide two integers in Java, the remainder will be removed and the answer will just be 2. [1] X Research source To use integer division, you’d use this syntax:

int a = 7; int b = 3; int result = a / b; // result will be 2 
  • Dividing two integers always results in an integer. If you want to get a decimal result from dividing two integers, use floating point division.
  • If you try to divide an integer by 0 using integer division, you’ll get an ArithmeticException error at runtime, even if the program compiles fine. [2] X Research source

Floating point division

Image titled 12966108 2

If either operand in the equation is of the float or double type, you’ll need to use float division. You can also use float division if you are dividing two numbers and want a decimal result. To use this division type, set the dividend and divisor to a float. [3] X Research source With our example of 7 divided by 3, our code would look like this:

float a = 7.0f; float b = 3.0f; int result = a / b; // result will be 2.33 
  • When dividing by zero with floating point division, the result will be NaN (Not a Number). [4] X Research source

Expert Q&A

When dividing mixed integer and floating point numbers, the floating point values (float or double) are automatically converted to the double type when dividing.

You Might Also Like

Set Java Home

How to Set JAVA_HOME for JDK & JRE: A Step-by-Step Guide

Check Your Java Version in the Windows Command Line

Use Easy Windows CMD Commands to Check Your Java Version

Compile & Run Java Program Using Command Prompt

Compile and Run Java Program by Notepad

How to Compile and Run Java Programs Using Notepad++

Calculate Percentage in Java

Add JARs to Project Build Paths in Eclipse (Java)

Check Null in Java

Install Java in Ubuntu Using Terminal

Program in Java

Create an Executable File from Eclipse

Call a Method in Java

Update Java

Check Java Version on a Mac

Print Double Quotes in Java

Simple Steps to Type a Bunny with Your Keyboard

About This Article

This article was co-authored by wikiHow staff writer, Nicole Levine, MFA. Nicole Levine is a Technology Writer and Editor for wikiHow. She has more than 20 years of experience creating technical documentation and leading support teams at major web hosting and software companies. Nicole also holds an MFA in Creative Writing from Portland State University and teaches composition, fiction-writing, and zine-making at various institutions. This article has been viewed 62,097 times.

Is this article up to date?

Quizzes

You Might Also Like

How to Set JAVA_HOME for JDK & JRE: A Step-by-Step Guide

Use Easy Windows CMD Commands to Check Your Java Version

How to Compile and Run Java Programs Using Notepad++

Источник

LeetCode #29 — Divide Two Integers

Hello fellow devs 👋! It’s a new day, and we have a new LeetCode problem in front of us.

Given two integers dividend and divisor , divide two integers without using multiplication, division, and mod operator.

Return the quotient after dividing dividend by divisor .

The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.

Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2 31 , 2 31 − 1]. For this problem, assume that your function returns 2 31 − 1 when the division result overflows.

Input: dividend = 10, divisor = 3 Output: 3 Explanation: 10/3 = truncate(3.33333..) = 3.
Input: dividend = 7, divisor = -3 Output: -2 Explanation: 7/-3 = truncate(-2.33333..) = -2.
Input: dividend = 0, divisor = 1 Output: 0
Input: dividend = 1, divisor = 1 Output: 1

If we read the description of the problem, it looks like that this is a simple division problem. However, if we read further, we find a constraint that we cannot use multiplication (x), division (/) and modulo (%) operations. This makes this problem a little tricky.

Also, one more constraint is that the result cannot be greater than 32-bit signed integer (from -2 31 to 2 31 — 1). If the result is outside this range, then we will return the minimum or maximum value of this range.

The biggest dilemma in front of us is that we cannot use multiplication (x), division (/) and modulo (%) operations. Then how the heck are we going to do this 🤔?

The first approach that comes to mind is that we start from quotient = 0 and loop until the dividend is greater than divisor and in each iteration, we subtract divisor from dividend . This seems to work fine and it also passes all the test cases but it is slow. Why? Let’s take an example — say, we have dividend = 2147483647 and divisor = 1 . In that case, the loop will run 2147483647 iterations which is obviously very slow.

How can we improve this 🤔? What if instead of decreasing the dividend linearly, we decrease it exponentially? This will definitely improve the performance drastically.

We can follow the below steps —

  1. A variable quotient will keep the track of answer.
  2. A while loop will check the condition dividend >= divisor
  3. Inside this while loop, we will have one variable shift which will left shift the divisor by one bit and check if the result is less than the dividend . This will repeat until the condition is false.
  4. Once, we are out of inner loop, then we will add the number of times we shifted to the quotient .
  5. Also, we will now subtract the result of shifting to divisor from the dividend for the next iteration. Remember that since in the while loop the value of shifting had gone beyond the dividend , the value we need to subtract is one bit less shifted.
  6. We will repeat the process unless we reach to the point where divisor is greater than dividend .

You must be wondering that why are we shifting the bits? The answer is, one left shift bit means the number is doubled. And since we cannot use multiplication, we are using left shifting.

Since the divisor is increasing exponentially, the time complexity will be O(log n).

No internal data structure has been used in the intermediate computations, the space complexity will be O(1).

public class DivideTwoIntegers  public int divide(int dividend, int divisor)  // Check for overflow if (divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1))  return Integer.MAX_VALUE; > // Sign of result int sign = (dividend > 0 && divisor  0) || (dividend  0 && divisor > 0) ? -1 : 1; // Quotient int quotient = 0; // Take the absolute value long absoluteDividend = Math.abs((long) dividend); long absoluteDivisor = Math.abs((long) divisor); // Loop until the dividend is greater than divisor while (absoluteDividend >= absoluteDivisor)  // This represents the number of bits shifted or // how many times we can double the number int shift = 0; while (absoluteDividend >= (absoluteDivisor  ))  shift++; > // Add the number of times we shifted to the quotient quotient += (1  <(shift - 1)); // Update the dividend for the next iteration absoluteDividend -= absoluteDivisor  <(shift - 1); > return sign == -1 ? -quotient : quotient; > >
class DivideTwoIntegers: def divide(dividend: int, divisor: int) -> int: # MAX and MIN values for integer MAX = 2147483647 MIN = -2147483648 # Check for overflow if divisor == 0 or (dividend == MIN and divisor == -1): return MAX # Sign of result` sign = -1 if (dividend > 0 and divisor  0) or (dividend  0 and divisor > 0) else 1 # Quotient quotient = 0 # Take the absolute value absoluteDividend = abs(dividend) absoluteDivisor = abs(divisor) # Loop until the dividend is greater than divisor while absoluteDividend >= absoluteDivisor: # This represents the number of bits shifted or # how many times we can double the number shift = 0 while absoluteDividend >= (absoluteDivisor  ): shift += 1 # Add the number of times we shifted to the quotient quotient += (1  <(shift - 1)) # Update the dividend for the next iteration absoluteDividend -= absoluteDivisor  <(shift - 1) return -quotient if sign == -1 else quotient
var divide = function (dividend, divisor)  const MAX = 2147483647; const MIN = -2147483648; // Check for overflow if (divisor === 0 || (dividend === MIN && divisor === -1))  return MAX; > if (divisor === dividend)  return 1; > // Sign of result const sign = (dividend > 0 && divisor  0) || (dividend  0 && divisor > 0) ? -1 : 1; // Quotient let quotient = 0; // Take the absolute value let absoluteDividend = Math.abs(dividend); let absoluteDivisor = Math.abs(divisor); // Loop until the dividend is greater than divisor while (absoluteDividend >= absoluteDivisor)  // This represents the number of bits shifted or // how many times we can double the number let shift = 0; let shiftedDivisor = absoluteDivisor; while (absoluteDividend >= shiftedDivisor)  shift++; shiftedDivisor = absoluteDivisor  ; // To handle overflow using left shift operator in JS if (shiftedDivisor  0)  break; > > // Add the number of times we shifted to the quotient quotient += (1  <(shift - 1)); // Update the dividend for the next iteration absoluteDividend -= absoluteDivisor  <(shift - 1); > return sign === -1 ? -quotient : quotient; >;
class DivideTwoIntegers  fun divide(dividend: Int, divisor: Int): Int  // Check for overflow if (divisor == 0 || dividend == Int.MIN_VALUE && divisor == -1)  return Int.MAX_VALUE > // Sign of result val sign = if (dividend > 0 && divisor  0 || dividend  0 && divisor > 0) -1 else 1 // Quotient var quotient = 0 // Take the absolute value var absoluteDividend = Math.abs(dividend.toLong()) val absoluteDivisor = Math.abs(divisor.toLong()) // Loop until the dividend is greater than divisor while (absoluteDividend >= absoluteDivisor)  // This represents the number of bits shifted or // how many times we can double the number var shift = 0 while (absoluteDividend >= absoluteDivisor shl shift)  shift++ > // Add the number of times we shifted to the quotient quotient += 1 shl shift - 1 // Update the dividend for the next iteration absoluteDividend -= absoluteDivisor shl shift - 1 > return if (sign == -1) -quotient else quotient > >

Congratulations 👏! Today we solved a new problem which uses bit manipulations.

I hope you enjoyed this post. Feel free to share your thoughts on this.

You can find the complete source code on my GitHub repository. If you like what you learn, feel free to fork 🔪 and star ⭐ it.

Till next time… Happy coding 😄 and Namaste 🙏!

Источник

Читайте также:  Hide page content php
Оцените статью