An alternative solution for 5.4 is:
def sameweight(word: Int) = {
var y = word & ~(word - 1)
if (y == 1) {
y = (word + 1) & ~(word)
}
val z = y >> 1
(word ^ y) ^ z
}
The insight here is: Find the least bit. If the least bit is not the last one then swap the first zero with the one next to it.
Let me know what you think about this?