5
5
* implementation
6
6
*
7
7
* @details
8
- * Given a number x, find next number with same number of 1 bits in it’s binary representation.
9
- * For example, consider x = 12, whose binary representation is 1100 (excluding leading zeros on 32 bit machine).
10
- * It contains two logic 1 bits. The next higher number with two logic 1 bits is 17 (100012).
8
+ * Given a number x, find next number with same number of 1 bits in it’s binary
9
+ * representation. For example, consider x = 12, whose binary representation is
10
+ * 1100 (excluding leading zeros on 32 bit machine). It contains two logic 1
11
+ * bits. The next higher number with two logic 1 bits is 17 (100012).
11
12
*
12
13
* A binary number consists of two digits. They are 0 & 1. Digit 1 is known as
13
14
* set bit in computer terms.
@@ -28,43 +29,39 @@ namespace bit_manipulation {
28
29
* @param x the number that will be calculated
29
30
* @returns a number
30
31
*/
31
- uint64_t next_higher_number (uint64_t x)
32
- {
33
-
34
- uint64_t rightOne;
35
- uint64_t nextHigherOneBit;
36
- uint64_t rightOnesPattern;
37
-
38
- uint64_t next = 0 ;
39
-
40
- if (x)
41
- {
42
-
43
- // right most set bit
44
- rightOne = x & -(signed )x;
45
-
46
- // reset the pattern and set next higher bit
47
- // left part of x will be here
48
- nextHigherOneBit = x + rightOne;
49
-
50
- // nextHigherOneBit is now part [D] of the above explanation.
51
-
52
- // isolate the pattern
53
- rightOnesPattern = x ^ nextHigherOneBit;
54
-
55
- // right adjust pattern
56
- rightOnesPattern = (rightOnesPattern)/rightOne;
57
-
58
- // correction factor
59
- rightOnesPattern >>= 2 ;
60
-
61
- // rightOnesPattern is now part [A] of the above explanation.
62
-
63
- // integrate new pattern (Add [D] and [A])
64
- next = nextHigherOneBit | rightOnesPattern;
65
- }
66
-
67
- return next;
32
+ uint64_t next_higher_number (uint64_t x) {
33
+ uint64_t rightOne = 0 ;
34
+ uint64_t nextHigherOneBit = 0 ;
35
+ uint64_t rightOnesPattern = 0 ;
36
+
37
+ uint64_t next = 0 ;
38
+
39
+ if (x) {
40
+ // right most set bit
41
+ rightOne = x & -static_cast <signed >(x);
42
+
43
+ // reset the pattern and set next higher bit
44
+ // left part of x will be here
45
+ nextHigherOneBit = x + rightOne;
46
+
47
+ // nextHigherOneBit is now part [D] of the above explanation.
48
+
49
+ // isolate the pattern
50
+ rightOnesPattern = x ^ nextHigherOneBit;
51
+
52
+ // right adjust pattern
53
+ rightOnesPattern = (rightOnesPattern) / rightOne;
54
+
55
+ // correction factor
56
+ rightOnesPattern >>= 2 ;
57
+
58
+ // rightOnesPattern is now part [A] of the above explanation.
59
+
60
+ // integrate new pattern (Add [D] and [A])
61
+ next = nextHigherOneBit | rightOnesPattern;
62
+ }
63
+
64
+ return next;
68
65
}
69
66
70
67
} // namespace bit_manipulation
0 commit comments