Find Odd and Even Numbers Using Bit Operation in Go



Examples

Input num = 5 => 101 & 1 = 001 => True, i.e., Odd; else num would be Even.

Approach to solve this problem

  • Step 1: Define a method that accepts a number.
  • Step 2: Perform & operation with that number.
  • Step 3: If the & operator returns a non-zero value, then that number would be odd.
  • Step 4: Else, the number would be even.

Program

Live Demo

package main
import "fmt"
func oddEven(num int){
   if num & 1 != 0 {
      fmt.Println("ODD")
   } else {
      fmt.Println("EVEN")
   }
}

func main(){
   oddEven(13)
   oddEven(50)
   oddEven(0)
}

Output

ODD
EVEN
EVEN
Updated on: 2021-02-04T11:31:15+05:30

514 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements