TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
next_higher_number_with_same_number_of_set_bits.cpp
Go to the documentation of this file.
1
18#include <cassert>
19#include <cstdint>
20#include <iostream>
21
26namespace bit_manipulation {
27
33uint64_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
74static void test() {
75 // x = 4 return 8
77 // x = 6 return 9
79 // x = 13 return 14
81 // x = 64 return 128
82 assert(bit_manipulation::next_higher_number(64) == 128);
83 // x = 15 return 23
85 // x= 32 return 64
87 // x = 97 return 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}
98int main() {
99 test(); // run self-test implementations
100 return 0;
101}
uint64_t next_higher_number(uint64_t x)
The main function implements checking the next number.
static void test()
Self-test implementations.