TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
find_non_repeating_number.cpp
Go to the documentation of this file.
1
18#include <cassert>
19#include <iostream>
20#include <vector>
21
26namespace bit_manipulation {
39int64_t find_non_repeating_integer(const std::vector<int>& nums) {
40 // The idea is based on the property of XOR.
41 // We know that 'a' XOR 'a' is '0' and '0' XOR 'b'
42 // is b.
43 // Using this, if we XOR all the elements of the array,
44 // the repeating elements will give '0' and this '0'
45 // with the single number will give the number itself.
46
47 int _xor = 0;
48
49 for (const int& num: nums) {
50 _xor ^= num;
51 }
52
53 return _xor;
54}
55} // namespace find_non_repeating_integer
56} // namespace bit_manipulation
57
62static void test() {
63 // n = 10,2 return 14
64
65 std::vector<int> nums_one{1, 1, 2, 2, 4, 5, 5};
66 std::vector<int> nums_two{203, 3434, 4545, 3434, 4545};
67 std::vector<int> nums_three{90, 1, 3, 90, 3};
68
69 assert(bit_manipulation::find_non_repeating_integer::
71 4); // 4 is non repeating
72 assert(bit_manipulation::find_non_repeating_integer::
74 203); // 203 is non repeating
75 assert(bit_manipulation::find_non_repeating_integer::
76 find_non_repeating_integer(nums_three) ==
77 1); // 1 is non repeating
78
79 std::cout << "All test cases successfully passed!" << std::endl;
80}
85int main() {
86 test(); // run self-test implementations
87 return 0;
88}
static void test()
Self-test implementations.
int main()
Main function.
Functions to find the non repeating integer in an array of repeating integers. Single Number