forked from anubhavshrimal/Data-Structures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNext_Number.cpp
More file actions
38 lines (27 loc) · 725 Bytes
/
Next_Number.cpp
File metadata and controls
38 lines (27 loc) · 725 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
Find the next greater and next smaller number with same number of set bits
*/
#include<iostream>
using namespace std;
// Ex. num = 6 bin = 110
int next_greater(int num) {
int res = num;
// at least one set bit
if (num != 0) {
// Find the right most 1 pos
// Ex. right_one = 2 bin = 10
int right_one = num & -num;
int left_pattern = num + right_one;
int right_pattern = (num ^ left_pattern) >> (right_one + 1);
res = left_pattern | right_pattern;
}
return res;
}
int previous_smaller(int num) {
return ~next_greater(~num);
}
int main() {
cout << next_greater(6) << endl;
cout << previous_smaller(6) << endl;
return 0;
}