The HackerRank challenge of today was a problem with conditionals. Given an integer $n$, the goal was to perform the following actions:
- If $n$ is odd, print
Weird
- If $n$ is even and in the range $[2, 5]$, print
Not Weird
- If $n$ is even and in the range $[6, 20]$, print
Weird
- If $n$ is even and greater than $20$, print
Weird
The input to the program is simply the number $n$ and the result is a single line saying that the number is weird or not. My solution was
package main
import "fmt"
func main() {
// read input
n := 0
fmt.Scanf("%v\n", &n)
var answer string
// Notice bitwise operation ->
// no division to check
if n&1 != 0 {
answer = "Weird"
} else {
if (n >= 2 && n <= 5) || n > 20 {
answer = "Not Weird"
} else {
answer = "Weird"
}
}
fmt.Println(answer)
}
There is a disclaimer though: I initially used n % 2 == 1
but this does an
integer division and when I saw that I could just use a bitwise operation to
check if the number was odd or not, I changed it.
That’s all for this post. Thanks for reading!