2017-08-04 23 views
-2

私はKattis "A Rational Sequence 2"に関する質問を完了し、2進数を10進数に変換できるより効率的な方法があるかどうかを知りたいと思っています。これは私のコードでした:より効率的なソリューションですか?

public static int getDecimalValue(String sequence){ 

    int value = 1; 

    for(int i = 0; i < sequence.length(); i++){ 
     if(sequence.charAt(i) == '1') 
      value += (int)Math.pow(2, i); 
    } 
    return value; 
} 

助けが素晴らしいでしょう!

+0

これが道でのJavaです... – WizardWy

+3

はこれを試してみてください。Integer.parseInt(binaryStringを、2) – subro

+0

あなたはInteger.parseInt使用することができます(シーケンスを、2); ... 2番目の引数は、ベースのためのものですバイナリの変換は2です... – 100rabh

答えて

0

int value = Integer.parseInt(sequence、2);

+0

これは彼が求めているものではありません... – bharath

+0

@bharathとなぜですか?効率のためにJREコードをチェックしましたか? –

0

いくつかの点があります。まず、コードに実際にエラーがあります。00000000(8個のゼロ)を渡してみて、何が起こるかを見てください。

効率性については、いくつか節約できます。あなたは長さを計算する場所を変更することができ、あなたはかなり遅いですbitshift計算することができます。

public static int getBinaryValue(String sequence){ 

    int value = 1; //have another glance at this line! 

    for(int i = 0, n=sequence.length(); i < n; i++){ 
    //I declared a variable 'n' in the initialisation, this means its only 
    //checked once, rather than being checked every time 
     if(sequence.charAt(i) == '1') 
      value += 1 << i; 
      //and here I've bitshifted the value. Basically I've said "take 
      //the number one and then shift it left down an imaginary binary 
      //track i times". So if i is three, for example, it'll shift it 
      //from 00000001 to 00000010 to 00000100 to 00001000, which is 8 
      //2^3 = 8 
    } 
    return value; 
} 
+0

ありがとう!私はまだビットの操作であまりにも良いではないので、私は間違いなくこの周りで遊ぶだろうが、あなたの説明は非常に良かった!感謝します! – WizardWy

関連する問題