TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
find_non_repeating_number.cpp
Go to the documentation of this file.
1
17
18
#include <cassert>
19
#include <iostream>
20
#include <vector>
21
26
namespace
bit_manipulation
{
33
namespace
find_non_repeating_integer
{
39
int64_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
62
static
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::
70
find_non_repeating_integer
(nums_one) ==
71
4);
// 4 is non repeating
72
assert(bit_manipulation::find_non_repeating_integer::
73
find_non_repeating_integer
(nums_two) ==
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
}
81
85
int
main
() {
86
test
();
// run self-test implementations
87
return
0;
88
}
test
void test()
Definition
caesar_cipher.cpp:100
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
bit_manipulation
for std::string
find_non_repeating_integer
Functions to find the non repeating integer in an array of repeating integers. Single Number.
bit_manipulation
find_non_repeating_number.cpp
Generated by
1.18.0