@Zombie_PG (ゾンビ)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

AtCoder Beginner Contest 014について(Java)

ABC014-Bのテストコードが足りない

テストケースにおいて何が不足しているのかが知りたいです。

image.png

実ソース

import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int X = scan.nextInt();

        StringBuilder Xreversed = new StringBuilder(Integer.toBinaryString(X)).reverse();
        int sum = 0;
        int bitJudge = Xreversed.length() % 4;
        if(bitJudge == 0){
            for(int i = 0; i < n; i++){
                if(Xreversed.toString().substring(i, i+1).equals("1")){
                    sum += scan.nextInt();
                }else{
                    scan.nextInt();
                }
            }
            System.out.println(sum);
        } else {
            // 4ビット区切り
            for(int i = 0; i < 4 - bitJudge; i++){
                Xreversed = Xreversed.append("0");    
            }
            // 出力
            for(int i = 0; i < n; i++){
                if(Xreversed.toString().substring(i, i+1).equals("1")){
                    sum += scan.nextInt();
                }else{
                    scan.nextInt();
                }
            }
            System.out.println(sum);
        }
    }
}
0 likes

1Answer

10 1
1 2 3 4 5 6 7 8 9 10

substring(i, i + 1)でエラーになります。

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 4, end 5, length 4
	at java.base/java.lang.String.checkBoundsBeginEnd(String.java:4601)
	at java.base/java.lang.String.substring(String.java:2704)
	at substring.Main.main(Main.java:30)

ソースコードですが、

int bitJudge = Xreversed.length() % 4;

4bit 区切りは必要ではありません。

こちらでいかがでしょうか。

    int sum = 0;
    for (int i = 0; i < Xreversed.length(); i++) {
      if (Xreversed.toString().substring(i, i + 1).equals("1")) {
        sum += scan.nextInt();
      } else {
        scan.nextInt();
      }
    }
    System.out.println(sum);

0Like

Your answer might help someone💌