Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
This article was originally published on Medium
Problem 1: Single Number
We are going to use this
XOR to solve the LeetCoder problem called Single number.
In this problem, an array input has a pair of numbers except one, for example
[1, 1, 5, 5, 2]. You need to find a sing number from this array and in this case the output should be
More example: When the input is
[2, 2, 1], the output should be
1. When an input is
[4, 1, 2, 1, 2] the output should be
This is a good example to use the
We briefly go through the Python solution to see how the problem was solved.
Line 1: We use Python
typing which is introduced from v3.5.
Line 3–4: After importing
List, we create a class called
Solution and method called
With Python type hints, we capitalize the name of the type, and set the name of the type inside the collection in brackets as seen above,
Line 5–8: We set a variable
ans to 0. Using a
for loop, we iterate the input array,
XOR compound assignment,
ans ^= n. This will output the single number from the array.
Line 10–11: We instantiate the class
Solution and call the method
(You can run this Python code without type notations if you are interested.)
The following is the solution for the LeetCode environment:
class Solution: def singleNumber(self, nums: List[int]) -> int: ans = 0 for n in nums: ans ^= n return ans
Rust structs contain named fields. We use a keyword
struct and set fields with its type within the curly bracket. We put methods into a
Line 1: We suppress
Line 2–4: Create a
Solution that takes one field
Vec<i32> type. (More on Vectors.)
Line 6–10: We create a method
impl Solution. The
single_number takes the first parameter
&self (More on
self .) and we just return
1 for now.
Line 12–17: In the main function, we create an instance and print
1 using the method.
It seems all working so we are going to complete the
single_number method next.