Group Group Group Group Group Group Group Group Group

Chapter 4 - Challenges problem 6 Source code Fixed


#1

Hello guys, I found a logic mistake in the source code that is been given with the book.

Given a number as a double value and determine if this number is a power of 2 by using a loop instead

o log2() function. It goes as follows.

val number = 1024.0 //The number you want to check if is a power of 2

var dividend = number
while ("%.0f".format(dividend % 2).toInt() == 0) {
dividend /= 2
}
if (dividend == 1.0) {
println("$number is a power of 2")
} else {
println("$number is not a power of 2")
}

Of course, you can make it using other loops as well. That one, it works fine!


#2

Thank you so much! I have confirmed your solution works and it will be in an updated version of the book.


#3

Actually, it’s simpler instead of using string.format(argument) and convert it to Int and then make the control,

just apply the variable as follows:

val number = 1024.0 //The number you want to check if is a power of 2

var dividend = number
while (dividend % 2 == 0.0) {
dividend /= 2.0
}
if (dividend == 1.0) {
println("$number is a power of 2")
} else {
println("$number is not a power of 2")
}


#4

Thanks for your feedback, great idea! No need to convert it to a string. I have updated the code and it will be shipped in the next version of the book.