w3resource

JavaScript - Maximum, minimum of two integers

JavaScript Bit Manipulation: Exercise-15 with Solution

Max/Min of Two Integers

Write a JavaScript program to calculate the maximum or minimum of two integers.

Test Data:
(12, 15) -> 15, 12
(-7,-5) -> -5, -7

Sample Solution:

JavaScript Code:

// Define a function to find the maximum and minimum of two numbers
const max_min = (x, y) => {
    // Calculate the maximum value using bitwise XOR and conditional operator
    let max = x ^ ((x ^ y) & -((x < y) ? 1 : 0));
    // Calculate the minimum value using bitwise XOR and conditional operator
    let min = y ^ ((x ^ y) & -((x < y) ? 1 : 0));
    // Return an object containing the maximum and minimum values
    return {a:max, b:min};
}

// Define two numbers
let x = 12;
let y = 15;

// Display the two numbers
console.log("Two numbers: " + x + "," + y);
// Call the max_min function to find the maximum and minimum values
const {a,b} = max_min(x, y);
// Display the maximum and minimum values
console.log("Maximum value: " +a + " and Minimum value: " +b);
// x = -7
// y = -5
// console.log("Two numbers: " + x + "," + y)
// const {a,b} = max_min(x, y)
// console.log("Maximum value: " +a + " and Minimum value: " +b)

Output:

Two numbers: 12,15
Maximum value: 15 and Minimum value: 12

Flowchart:

Flowchart: JavaScript - Maximum, minimum of two integers.

Live Demo:

See the Pen javascript-bit-manipulation-exercise-15 by w3resource (@w3resource) on CodePen.


* To run the code mouse over on Result panel and click on 'RERUN' button.*

For more Practice: Solve these Related Problems:

  • Write a JavaScript function that uses bitwise operations to compute the maximum of two integers without using Math.max.
  • Write a JavaScript function that uses bitwise operations to compute the minimum of two integers without using Math.min.
  • Write a JavaScript function that compares two integers by subtracting them and analyzing the sign of the result.
  • Write a JavaScript function that validates that both inputs are integers before performing the max/min calculation.

Go to:


PREV : Non-Repeated Element.
NEXT : JavaScript DOM Exercises Home.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.