1

ここで見つけた小さなパズルを試していました

なぜ私の答えが間違っているのだろうと思っていましたが、元の仕様は

あなたの仕事は、2 進数で数値を逆にするプログラムを書くことです。たとえば、13 の 2 進数表現は 1101 で、これを逆にすると 1011 となり、これは数字の 11 に対応します。

だからここに私のコードです..

import java.util.Scanner;

public class ReverseBinary {

    public  String reversedIntToBinary(int val) {
        int value = val;
        StringBuilder bldr = new StringBuilder();

        while (value != 0) {
            int remainder = value % 2;
            value = value / 2;
            bldr.append(remainder);
        }
        return bldr.toString();
    }

    public  int toDecimal(String bin) {
        char[] binString = bin.toCharArray();

        int starting = 0;

        for (int i = 0; i < binString.length; i++) {
            int tempoVal = starting * 2
                    + Character.getNumericValue(binString[i]);
            starting = tempoVal;
        }
        return starting;
    }

    public  int reversedBinary(int val){
        String bin =reversedIntToBinary(val);
        int result = toDecimal(bin);
        return result;
    }

    public static void main(String[] args) {
        ReverseBinary rvb = new ReverseBinary();

        Scanner input = new Scanner( System.in);
        System.out.println("Enter A Number: ");
        int num = input.nextInt();
        System.out.println(rvb.reversedBinary(num));
    }
}

それは上記のタスクを実行していますが、私の提出では間違っています。なぜそれが間違っていると考えられているのだろうか?私は何か重要なことを逃しましたか?

4

4 に答える 4

3

N の 2 進数表現を反転して得られる整数 1 を含む 1 行を出力します (強調を追加)。

2Enter A Number:と整数を出力しています。テキストEnter A Number:\n11\nがテキストと等しくありません11\n。自動システムを使用してプログラムをチェックしている場合、その理由で提出が失敗する可能性があります。

(私はそれ以外のコードをチェックしていないので、他の問題もあるかもしれませんが、それはすぐに目立ちます。)

于 2013-02-26T15:45:03.977 に答える
0
int result = Integer.reverse( value );
while((result & 1) == 0 && result != 0)
    result >>= 1;

edit AND と SHIFT を使用したビット位置補正を追加

public static int reverse(int i)

Returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified int value.

Returns:
    the value obtained by reversing order of the bits in the specified int value.
Since:
    1.5
于 2013-02-26T15:47:50.367 に答える
0

私のソリューションをチェックしてください: https://github.com/nzpetter/reversebinary

Spotify のパズルを解くとき、私は 1 つのことを学びました。車輪を発明しようとしないでください。おそらく、誰かがあなたが必要とするメソッドをすでに作成しているでしょう。

public static int reversebinary(int s) {
    return Integer.parseInt(new StringBuilder(Integer.toBinaryString(s)).reverse().toString(), 2);
}
于 2013-02-27T21:16:49.427 に答える
0

2 進数の最大サイズ (この例では 4 ビット) が分かっていて、それが 8 ビット以下である場合、反転を実行する最速の方法は、現在の 2 進数値をインデックスとして使用するルックアップ テーブルを使用することです。例えば、

// indices 0 - 3 of the lookup table.
byte[] lookUpTable =
{
  0b0000, 0b1000, 0b0100, 0b1100
}

// assuming a valid index.
byte reversed = lookUpTable[valueToReverse];
于 2013-02-26T15:46:35.453 に答える