import scala.collection.mutable import scala.io.StdIn object Problem003 { def bitCount(i: Int): Int = Integer.bitCount(i) def proc(goal: Int): Int = { def inField(i: Int): Boolean = 1 <= i && i <= goal val dp = Array.fill(goal + 1)(Int.MaxValue) dp(1) = 0 val queue = new mutable.Queue[Int]() queue += 1 while (queue.nonEmpty) { def enqueue(currentPlace: Int, nextSteps: Int): Unit = { if (inField(currentPlace) && dp(currentPlace) > nextSteps) { queue += currentPlace dp(currentPlace) = nextSteps } } val s = queue.dequeue() if (s == goal) return dp(goal) + 1 val back = s - bitCount(s) val forward = s + bitCount(s) val nextSteps = dp(s) + 1 enqueue(back, nextSteps) enqueue(forward, nextSteps) } -1 } def main(args: Array[String]) { val n = StdIn.readInt() val result = proc(n) println(result) } }