2011-05-11 30 views
0

如何獲得值one,twothree回? 以下方法是否正確?看起來不是。如何解碼編碼爲一個* 100 +兩個* 10 +三的值?

int EncodedValue = one*100 + two*10 + three; 

// the following decryption is part of another procedure 
int one = EncodedValue/100; 
int two = EncodedValue/10; 
int three = EncodedValue % 10; 
+0

一,二和三總是在0..9 – 2011-05-11 19:21:43

+0

您應該編輯您的評論到問題中。 – 2011-05-11 19:30:44

回答

5

假設twothree原來在範圍0-9(否則你有歧義)你想:

int two = (encodedValue/10) % 10; 

...否則它基本上被添加到其十倍的one值。

+0

您的假設確實在OP的評論中。 – mellamokb 2011-05-11 19:27:41

+0

@mellamokb:糟糕 - 我看到有評論,我沒有意識到它來自OP(快速瀏覽)。 – 2011-05-11 19:30:31

1

這不會奏效。雖然我不能說下面的效率,但它的工作:

int encoded = one*100+two*10+three 
int one = encoded/100; 
int two = (encoded-100*one)/10; 
int three = encoded - 100*one - 10*two; 

請注意,這隻適用於如果所有這些變量都是單個數字。 它也可以遞歸地實現,以允許任何長度的數字被分解爲它們的數字,但是它可能不那麼簡單,只是轉換爲一個字符串然後是一個字符數組。