TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
next_higher_number_with_same_number_of_set_bits.cpp
Go to the documentation of this file.
1
17
18
#include <cassert>
19
#include <cstdint>
20
#include <iostream>
21
26
namespace
bit_manipulation
{
27
33
uint64_t
next_higher_number
(uint64_t x) {
34
uint64_t rightOne = 0;
35
uint64_t nextHigherOneBit = 0;
36
uint64_t rightOnesPattern = 0;
37
38
uint64_t next = 0;
39
40
if
(x) {
41
// right most set bit
42
rightOne = x & -
static_cast<
signed
>
(x);
43
44
// reset the pattern and set next higher bit
45
// left part of x will be here
46
nextHigherOneBit = x + rightOne;
47
48
// nextHigherOneBit is now part [D] of the above explanation.
49
50
// isolate the pattern
51
rightOnesPattern = x ^ nextHigherOneBit;
52
53
// right adjust pattern
54
rightOnesPattern = (rightOnesPattern) / rightOne;
55
56
// correction factor
57
rightOnesPattern >>= 2;
58
59
// rightOnesPattern is now part [A] of the above explanation.
60
61
// integrate new pattern (Add [D] and [A])
62
next = nextHigherOneBit | rightOnesPattern;
63
}
64
65
return
next;
66
}
67
68
}
// namespace bit_manipulation
69
74
static
void
test
() {
75
// x = 4 return 8
76
assert(
bit_manipulation::next_higher_number
(4) == 8);
77
// x = 6 return 9
78
assert(
bit_manipulation::next_higher_number
(6) == 9);
79
// x = 13 return 14
80
assert(
bit_manipulation::next_higher_number
(13) == 14);
81
// x = 64 return 128
82
assert(
bit_manipulation::next_higher_number
(64) == 128);
83
// x = 15 return 23
84
assert(
bit_manipulation::next_higher_number
(15) == 23);
85
// x= 32 return 64
86
assert(
bit_manipulation::next_higher_number
(32) == 64);
87
// x = 97 return 98
88
assert(
bit_manipulation::next_higher_number
(97) == 98);
89
// x = 1024 return 2048
90
assert(
bit_manipulation::next_higher_number
(1024) == 2048);
91
92
std::cout <<
"All test cases have successfully passed!"
<< std::endl;
93
}
94
98
int
main
() {
99
test
();
// run self-test implementations
100
return
0;
101
}
test
void test()
Definition
caesar_cipher.cpp:100
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
bit_manipulation
for std::string
bit_manipulation::next_higher_number
uint64_t next_higher_number(uint64_t x)
The main function implements checking the next number.
Definition
next_higher_number_with_same_number_of_set_bits.cpp:33
bit_manipulation
next_higher_number_with_same_number_of_set_bits.cpp
Generated by
1.18.0