0
I would like to ask for a way to improve the second code I wrote while still using the xor operation for it.
first of all I would like to share what I have learnt about bits and bits operations for anyone who may find it helpful ,secondly ask for improvement of the code in the second link while still using the xor operation for it https://code.sololearn.com/cPS7v3nbkV9P/?ref=app https://code.sololearn.com/cljRFMluOoGL/?ref=app
2 Answers
+ 2
Unfortunately, because of Sololearn's bad linking, your code cannot be opened from the mobile app.
I checked it through the web playground.
The link that works from mobile:
https://code.sololearn.com/cljRFMluOoGL/?ref=app
Your code is badly formatted, you have unused libraries, and unused variables, so it is hard to read.
You missed
- giving a task description: what your program is trying to solve
- giving a sample input, so that people can test your code
Using XOR in this situation is meaningless because you could just as well compare the elements directly for equality, rather than comparing their XOR with 0.
Maybe you meant to solve a task, where there is a range of consecutive number, for example 2, 3, 4, 5, 6 - in random order, and additionally one of the values is duplicated.
Here is the code refactored by me (but it can easily be a solution to a different problem than what you had in mind)
https://code.sololearn.com/c58u4jzeDDbD/?ref=app
Here the benefit of using XOR is performance! Because I do not need an extra array, the space complexity is O(0) constant. And I only make 3 passes through the array without nested loops, so the time complexity is O(n) linear. In your solution you have a nested loop, which makes the complexity exponential. Imagine if you have a large array, like with a million elements, then the code must do million times million iterations.
You should check this post also:
https://stackoverflow.com/questions/10764286/using-xor-operator-for-finding-duplicate-elements-in-a-array-fails-in-many-cases
+ 1
Tibor Santa
Regarding the fact that there is no need to use the xor operator i fully agree lol , i already wrote a code that does the same thing using an unordered map which is more effictive ,yet this code is infact for practice in order to get used to using the xor operator , so i was trying to find a way toimproce the code while still using the xor operator (especially since i added a nested loop which is not ideal at all )to do the same task as a mean to learn about new ways to implement it or thats what i had in mind , but i think the post you added will teach me useful stuff as well thx for the comment
https://code.sololearn.com/cnevLq41aCqo/?ref=app