0; $n >>= 1) { $ans += $n & 1; } return $ans; } $n = trim(fgets(STDIN)); $a = array(); for ($i = 0; $i <= $n; $i++) $a[$i] = -1; $a[1] = 1; $queue = array(1); while (count($queue) > 0) { $m = array_pop($queue); $bc = substr_count(decbin($m), 1); if ($m - $bc > 0 && ($a[$m - $bc] == -1 || $a[$m - $bc] > $a[$m] + 1)) { $a[$m - $bc] = $a[$m] + 1; array_unshift($queue, $m - $bc); } if ($m + $bc <= $n && ($a[$m + $bc] == -1 || $a[$m + $bc] > $a[$m] + 1)) { $a[$m + $bc] = $a[$m] + 1; array_unshift($queue, $m + $bc); } } print $a[$n];