Skip to content

Commit 0ade418

Browse files
authored
add more comments
1 parent f2291a2 commit 0ade418

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

algorithms/cpp/decodeXORedPermutation/DecodeXoredPermutation.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,53 @@
3030
* n is odd.
3131
* encoded.length == n - 1
3232
******************************************************************************************************/
33+
/*
34+
XOR Basic Rules
35+
---------------
36+
At first, we need understand the following XOR rules
3337
38+
x^x = 0
39+
0^x = x
40+
with the rule 1 and 2 , we can have: x^x^y = y . the element ocurrs twice would be removed.
41+
if x^y = z , then x = y^z and y = x^z
42+
43+
XOR from 1 to n
44+
---------------
45+
Secondly, suppose the f(n) is XOR from 1 to n , f(n) = 1^2^3^4^5 .... ^n .
46+
if the n is odd number, then we can observse the following things:
47+
48+
f(1) = 1
49+
f(3) = 1^2^3 = 0
50+
f(5) = 1^2^3^4^5 = 1
51+
f(7) = 1^2^3^4^5^6^7 = 0
52+
f(9) = 1^2^3^4^5^6^7^8^9 = 1
53+
... ...
54+
so, f(n) = [ (n-1)/2 + 1 ] % 2 - (n is odd number)
55+
56+
Solution
57+
--------
58+
We know,
59+
encode = { (p1^p2), (p2^p3), (p3^p4), ... } - p is the permutation array
60+
61+
so, if xor the odd index of encoded[] array,
62+
63+
encoded[1] = p2 ^ p3;
64+
encoded[3] = p4 ^ p5;
65+
encoded[5] = p6 ^ p7;
66+
......
67+
we can get: f(m) = p2 ^ p3 ^ p4 ...pn, without the p1
68+
69+
with the XOR rule 3, we know
70+
71+
p1 = f(n) ^ f(m)
72+
73+
with the XOR rule 4, we know encoded[0] = p1^p2 then
74+
p2 = p1 ^ enclode[0]
75+
76+
So,
77+
78+
p[i+1] = p[i] ^ enclode[i]
79+
*/
3480
class Solution {
3581
public:
3682
vector<int> decode(vector<int>& encoded) {

0 commit comments

Comments
 (0)