I solved a problem on exercism that involved bit shifting.

There is a chess board with 64 squares, a grain of wheat is placed on the 
first square, for the second square you double the number of grains from 
the first (1 +1) = 2. For the third you double the previous (2 + 2) = 4. 
Continue this until the board is full.

The total function below is to add up all the grains on all the squares to 
know how many grains are on the board.

I defined grains as a uint64, shifted it and then returned the answer.

func Total() uint64 { 
  var grains uint64 = 1 
  return (grains << 64) - 1 
}

The mentor told me that is not needed. Modified the solution to look like 
this below
func Total() uint64 {
 return (1 << 64) - 1 
}
And it still worked!!
Which is something I was definitely not expecting. How does the compiler 
know the right amount of memory to allocate to the literal 1.

Thanks

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/ceaa1baa-ca80-46e2-b6f5-2112adef17e9n%40googlegroups.com.

Reply via email to