Repository navigation
Expand file tree
/
Copy pathBitManipulation.cpp
More file actions
157 lines (125 loc) · 2.19 KB
/
Copy pathBitManipulation.cpp
File metadata and controls
157 lines (125 loc) · 2.19 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#include <iostream>
#include <vector>
#include <string>
#include <utility>
#include <cmath>
#include <algorithm>
#include <limits.h>
#include <typeinfo>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <unordered_map>
using namespace std;
// Even-Odd
void CheckEvenOdd(int n){
if(n & 1) {
cout << "Odd" << endl;
}
else {
cout << "Even " << endl;
}
return;
}
// Get ith Bit
void GetIthBit(int n, int i){
int mask = (1 << i);
int ans = n & mask;
if(ans == 0) {
cout << "bit-> 0" << endl;
}
else {
cout << "bit-> 1" << endl;
}
return;
}
// Set ith Bit
void SetIthBit(int &n, int i){
int mask = (1<<i);
n = n | mask;
return;
}
// Clear ith Bit (1->0)
void ClearIthBit(int &n, int i){
int mask = ~(1<<i);
n = n & mask;
return;
}
// Update ith Bit
void UpdateIthBit(int &n, int i, int target){
// Clear ith bit
ClearIthBit(n, i);
int mask = (target << i);
n = n | mask;
return;
}
// Clear last i Bits
void ClearLastIBits(int &n, int i){
int mask = (-1 << i);
n = n & mask;
return;
}
// Check Power of 2, Set-Bits == 1;
bool CheckPowerOfTwo(int n) {
if(n <= 0) {
return false;
}
int count = 0;
// Count set-bits
while(n != 0) {
int lastbit = n & 1;
if(lastbit) {
count++;
if(count > 1) {
return false;
}
}
n = n >> 1;
}
return true;
}
// Fast way to Check Power of 2, Set-Bits == 1;
bool fastCheckPowerOf2(int n){
if((n & (n-1)) == 0){
return true;
}
return false;
}
// Fast way to count Set-Bits
int fastCountSetBits(int n){
int count = 0;
while(n != 0){
count++;
n = (n & (n-1));
}
return count;
}
// Clear range
void clearBitsInRange(int n, int i, int j){
int a = (-1 << (i+1));
int b = ~(-1 << j);
int mask = a | b;
n = n & mask;
}
// Subsequence of String
vector<string> GetSubsequences(string str){
int n = str.length();
vector<string> ans;
// 1 is include, 0 is exculde
for(int num = 0; num < (1<<n); num++ ){
string temp = "";
for(int i=0; i<n; i++) {
char ch = str[i];
int mask = (1 << i);
if(num & mask) {
temp.push_back(ch);
}
}
ans.push_back(temp);
}
return ans;
}
int main(){
return 0;
}