0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

bit Sugoroku

Posted at

課題文

Carol は特殊なすごろくをしようとしている。

1からNの番号がふられている一直線に並べられているN個のマスがある。
1から開始のマスとして、ゴールはNが書かれているマスとする。

その場に書かれている数字の2進数で表現した時の1のビット数 だけ「前」または「後」に進めることができる。
(1未満とN+1以上のマスには移動することは出来ない、正確にNにならないとゴールできない)

自然数Nを与えられた時、ゴールに到達できる最短の移動数(開始のマスへも移動にカウントする)を求めてください。
到達できない場合は-1を出力してください。

開始のマスがすでにゴールになっている場合もあリます。

入力値 N

マスの数を表す整数N(1≤N≤10000)が与えられます。

ソース

<?php
//入力値
$nyu = 1;

//結果値となる元
$number = 1;
$here = 1;
$array = [1];

//入力値を2進数に変換して1bitだけ取得する
for ($i=1; $i<$nyu; $i++) {
    $number_2sin = decbin($here);
    $bit1 = substr_count( $number_2sin, 1 );
    $number++;

    if ( ($here + $bit1) == $nyu ) {
        break;
    } 
    elseif ( ($here + $bit1) > $nyu ) {
        $here = $here - $bit1;
        if (array_search($here, $array) !== FALSE) {
            $counter = -1;
            break;
        }
    }
    else {
        $here = $here + $bit1;
    }
    $array[] = $here;
}
echo $number."\n";

?>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?