Find Minimum and Maximum Number Using Binary Operations in Go



Examples

For example, x = 12, y = 15 => Maximum number is 15.

For example, x = 13, y = 17 => Minimum number is 13.

Approach to solve this problem

Step 1 − Define method, findMax and findMin, that accept two integer x and y.

Step 2 − Return integer according to defined method.

Example

 Live Demo

package main
import "fmt"
func FindMax(x, y int){
   fmt.Printf("Maximum element in %d, and %d is: %d\n", x, y, x - ((x - y) &
   ((x - y) >> 31)))
}
func FindMin(x, y int) {
   fmt.Printf("Minimum element in %d, and %d is: %d\n", x, y, y + ((x - y) &
   ((x - y) >> 31)))
}
func main(){
   FindMax(12, 15)
   FindMin(13, 17)
   FindMax(1, 0)
}

Output

Maximum element in 12, and 15 is: 15
Minimum element in 13, and 17 is: 13
Maximum element in 1, and 0 is: 1
Updated on: 2021-03-17T11:39:20+05:30

208 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements