The HackerRank challenge of today was a problem with conditionals. Given an integer , the goal was to perform the following actions:
- If is odd, print
Weird - If is even and in the range , print
Not Weird - If is even and in the range , print
Weird - If is even and greater than , print
Weird
The input to the program is simply the number 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!