2011-05-11 25 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; 

请注意,这只适用于如果所有这些变量都是单个数字。 它也可以递归地实现,以允许任何长度的数字被分解为它们的数字,但是它可能不那么简单,只是转换为一个字符串然后是一个字符数组。