N = $n; } public function changeBinary($num = 0) { $binary = array(); if(!$num) return 0; for ($tmp_num = $num; $tmp_num >= 1; $tmp_num /= 2){ if($tmp_num % 2 == 1) { $tmp_num--; array_unshift($binary, 1); } else { array_unshift($binary, 0); } } return implode('', $binary); } public function countBinaryOne($num) { $binary = $this->changeBinary($num); return substr_count($binary, 1); } public function init() { $this->count_min = 0; } public function searchStart() { $this->init(); $this->loop(); if($this->count_min > 0) { return $this->count_min; } return -1; } public function checkGoal($num) { if($num != $this->N) return false; return true; } public function checkRoute($num) { if($num < 1) return false; elseif($num > $this->N) return false; return true; } public function loop($now = 1, $count = 1, $passed = array()) { if(!$this->checkRoute($now)) { return false; } elseif(isset($passed[$now]) && $passed[$now] === true) { return false; } if($this->checkGoal($now)) { if($this->count_min == 0 || $this->count_min > $count) { $this->count_min = $count; } return true; } $passed[$now] = true; $binary_one_check = $this->countBinaryOne($now); $this->loop($now + $binary_one_check, $count + 1, $passed); $this->loop($now - $binary_one_check, $count + 1, $passed); } } while($input = fgets(STDIN)) { $class = new MyClass((int)$input); echo $class->searchStart() . PHP_EOL; }