LoginSignup
5
5

More than 5 years have passed since last update.

ナンバーマジック

Posted at

 う〜ん・・・解けたは解けたけど・・・bitを用いて全探索した気がしないなぁ。肩すかしを食らった気分です(笑)やった事は、ただビットへ変換を行って、それを配列の要素(ビットで考慮)と比較して一致していたら添字+1を出力ってだけなので構造はかなり単純です。
問題元:SRM484 Div2 Level1
問題文:
 タローがハナコに手品を見せようとしています。
タロー:ハナコさんこんにちは。手品を見せて挙げようか?16以下の正の整数を頭の中で思い浮かべ    てみてくれる?
ハナコ:OK。思い浮かべたわ。
タロー:(ハナコにカード1を見せながら)このカードの中にハナコさんの数字、入っている?
ハナコ:あるわ。
タロー:(ハナコにカード2を見せながら)このカードの中にハナコさんの数字、入っている?
ハナコ:ないわ。
タロー:(ハナコにカード3を見せながら)このカードの中にハナコさんの数字、入っている?
ハナコ:あるわ。
タロー:(ハナコにカード4を見せながら)このカードの中にハナコさんの数字、入っている?
ハナコ:あるわ。
タロー:ハナコさんの数字は、5ですね!
各カード集合の中身:
Card1:1, 2, 3, 4, 5, 6, 7, 8
Card2:1, 2, 3, 4, 9, 10, 11, 12
Card3:1, 2, 5, 6, 9, 10, 13, 14
Card4:1, 3, 5, 7, 9, 11, 13, 15

この手品をシミュレートするプログラムを書いてください。ハナコの回答が文字型変数answerで与えられます。i番目の文字が'Y'であれば、i番目のハナコの回答は"YES"です。'N'であれば、i番目のハナコの回答は"NO"です。ハナコが頭の中で思い浮かべた数字をinteger型で返してください。

public class Main {
    int theNumber(String answer) {
        int[] ary = {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; //この要素に当てはまる数は答えが(r + 1)となる
        int sum = 0;
        int count = 0;
        for(int r = 3; r >= 0; r--) {
            if(answer.charAt(r) == 'Y') {
                sum += Math.pow(2, count); //Math.pow()は第3引数をとるので本来ならばあまり推奨されない。
            }
            count++;
        }
        int ans = 0;
        for(int r = 0; r < ary.length; r++) {
            if(sum == ary[r]) {
                ans = r + 1;
            }
        }
        return(ans);
    }

    void doIt() {
        String[] str = {"YNYY", "YNNN", "NNNN", "YYYY", "NYNY"};

        System.out.println((theNumber(str[0])));
        System.out.println((theNumber(str[1])));
        System.out.println((theNumber(str[2])));
        System.out.println((theNumber(str[3])));
        System.out.println((theNumber(str[4])));
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new Main().doIt();
    }
}
5
5
7

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
5
5