2017-08-04 105 views
-2

我剛剛完成了關於Kattis「A Rational Sequence 2」的一個問題,並想知道是否有更有效的方法可以將二進制數轉換爲十進制數。這是我的代碼:更有效的解決方案?

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 ... – 100rabh

回答

0

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

+0

這不是他要求的... – bharath

+0

@bharath,爲什麼不呢?你是否檢查了JRE代碼的效率? –

0

幾點。首先,你的代碼中實際存在一個錯誤 - 嘗試傳遞它00000000(8個零),看看會發生什麼。

至於效率,您可以節省一些成本。你可以改變你計算長度的位置,你可以計算,這比計算速度要快很多。

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