JavaScript - Maximum, minimum of two integers
JavaScript Bit Manipulation: Exercise-15 with Solution
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:
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.*
Improve this sample solution and post your code through Disqus.
Previous: Find the non-repeated element from an array.
Next: JavaScript DOM Exercises Home.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/bit-manipulation/bit-manipulation-exercise-15.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics