-
Notifications
You must be signed in to change notification settings - Fork 1
/
Bit Manipulation.txt
418 lines (356 loc) · 10.7 KB
/
Bit Manipulation.txt
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
Solutions of these questions are either on GFG or LEETCODE
---------------------------------------Bit Manipulation-----------------------------------------
1. Count Set Bits
public static int countbits(int n) {
int ans = 0;
while (n > 0) {
ans += (n & 1);
n = n >> 1;
}
return ans;
}
#Kernighan's Algorithm->
->//two's compliment -> either -n or (~n+1);
public static int countBits(int n) {
int c=0;
while(n!=0) {
int rsbm=n&(-n); //rsbm-> right most set bit mask (n&(two's compliment of n))
n-=rsbm;
c++;
}
return c;
}
public static int countbitsfast(int n) {
int ans = 0;
while (n > 0) {
n = n & (n - 1); // this will remove last set bit from right to left.
ans++;
}
return ans;
}
-> in O(N)
public int[] countBits(int n) {
// https://leetcode.com/problems/counting-bits/discuss/79557/How-we-handle-this-question-on-interview-Thinking-process-%2B-DP-solution
// O(N) <- there is a pattern just dry run to understand and also see the above discussion
int[]res = new int[n+1];
int offset=1;
for(int index=1;index<n+1;index++){
if(offset*2==index){
offset*=2;
}
res[index]=res[index-offset]+1;
}
return res;
}
----------------------------------------------------------------------------------------------
2. Decimal to Binary
private static int dectobin(int n) {
int ans = 0;
int p = 1;
while (n > 0) {
int lastbit = n & 1;
ans += lastbit * p;
p *= 10;
n = n >> 1;
}
return ans;
}
----------------------------------------------------------------------------------------------
3. Fast Exponentiation Optimized
public static int power_optimised(int a, int n) {
int ans = 1;
while (n > 0) {
int lastbit = (n & 1);
if (lastbit == 1) {
ans = ans * a;
}
a = a * a;
n = n >> 1;
}
return ans;
}
----------------------------------------------------------------------------------------------
4. Get Set Clear Update
private static boolean isodd(int n) {
if ((n & 1) == 1) {
return true;
}
return false;
}
public static int getbit(int n, int i) {
int mask = 1 << i;
int bit = (n & mask) > 0 ? 1 : 0;
return bit;
}
public static int setbit(int n, int i) {
int mask = 1 << i;
int ans = (n | mask);
return ans;
}
#Important{~0 or -1 gives all 1's}
public static int clearbit(int n, int i) {
int mask = ~(1 << i);
int ans = (n & mask);
return ans;
}
public static int updatebit(int n, int i, int v) {
int mask = (v << i);
int cleared_bit_no = clearbit(n, i);
int ans = (cleared_bit_no | mask);
return ans;
}
public static int clearlastibits(int n, int i) {
int mask = (~0 << i);// or you can write (-1<<i)
return n & mask;
}
#important -> 2^i-1 gives 0111 like mask for eg 16-1=15(0111)
public static int clearrangeofbits(int n, int i, int j) {
int ones = (~0); // = -1;
int a = (ones) << (j + 1);
int b = (1 << i) - 1; //2^i-1
int mask = (a | b);
int ans = n & mask;
return ans;
}
->Replace Bits In N by M range(i,j) 'i' from left, to right 'j'
public static int replacebits(int n, int m, int i, int j) {
int nn = clearrangeofbits(n, i, j);
int ans = nn | (m << i);
return ans;
}
----------------------------------------------------------------------------------------------
5. Subsets of a String
private static void printsubsets(char[] a) {
int n = a.length;
for (int i = 0; i < (1 << n); i++) {
filterChars(i, a);
}
}
private static void filterChars(int n, char[] a) {
int j = 0;
while (n > 0) {
int lastbit = (n & 1);
if (lastbit == 1) {
System.out.print(a[j]);
}
j++;
n = n >> 1;
}
System.out.println();
}
----------------------------------------------------------------------------------------------
6. Unique No.1
Logic-> take a variable ans=0 then xor it with all the elements of the array=>{ ANS=ANS^arr[i] };
Unique No. 2
->public int[] singleNumber(int[] nums)
{
int xor=0;
for(int i=0;i<nums.length;i++){
xor=xor^nums[i];
}
int[] ans=new int[2];
int temp=xor;
int pos=0;
while((temp&1)!=1){
temp=temp>>1;
pos++;
}
int mask=1<<pos;
int x=0;
for(int i=0;i<nums.length;i++){
if((nums[i]&mask)>0){
x=x^nums[i];
}
}
int y=xor^x;
ans[0]=Math.min(x,y);
ans[1]=Math.max(x,y);
return ans;
}
Unique No. 3
int n = scn.nextInt();
int[] cnt = new int[64];
int inp;
for (int i = 0; i < n; i++) {
inp = scn.nextInt();
// update the count array by extracting bits.
int j = 0;
while (inp > 0) {
int lastbit = (inp & 1);
cnt[j] += lastbit;
j++;
inp = inp >> 1;
}
}
// iterate the array and from the answer by converting 0s and 1s into a number.
int p = 1;
int ans = 0;
for (int i = 0; i < cnt.length; i++) {
cnt[i] = cnt[i] % 3;
ans += cnt[i] * p;
p = p << 1;
}
System.out.println(ans);
----------------------------------------------------------------------------------------------
7. Count Total set bits from 1 to N in (LogN)->https://www.youtube.com/watch?v=g6OxU-hRGtY
//Dry run this code for better explaination (eg.->dry run for 11)
public static int TotalSetBits1toN(int n){
if(n==0){
return 0;
}
int x=largestpowerof2inrange(n);
int btill2x=(1<<(x-1))*x; //bits upto 2 raise x-1; eg-> 1 to 7
int msb2xton=(n-(1<<x)+1); //MSB from 2 raise x to n; eg-> 8 to 11 msb's
int rest=n-(1<<x); //11-8 -> now find bits for (0 1 2 3)
int ans=btill2x+msb2xton+TotalSetBits1toN(rest);
return ans;
}
public static int largestpowerof2inrange(int n){
//in range means it can be less than equal to n for eg->8(2^3) for 11
int x=0;
while((1<<x)<=n){
x++;
}
return x-1;
}
----------------------------------------------------------------------------------------------
8. Count number of bits to be flipped to convert A to B
Logic-> take a var c=a^b, now find no of set bits in c , which is the ans;
this is because xor will help in finding the bits which are different as we know (xor gives value 1 on different bits)
----------------------------------------------------------------------------------------------
9. Program to find whether a no is power of two
->if(n==0)return false;
return ((n&(n-1))==0); for eg-> 16&15 gives 0 which is divisible by 2
----------------------------------------------------------------------------------------------
10. Copy Set Bits in a Range->https://www.youtube.com/watch?v=v7pUZw-ZOYU&list=PL-Jc9J83PIiFJRioti3ZV7QabwoJK6eKe&index=23
//write your code here
int mask=(1<<(right-left+1)); //right here is actually at left,and vice versa
mask--;
mask=(mask<<(left-1));
mask=a&mask;
b=mask|b;
System.out.println(b);
----------------------------------------------------------------------------------------------
Binary Number= 101110111 | 01 here i put spit in this , the position of split depends upon the power of two, means here this number if divided by 4 leaves quotient in the left part and remainder in the right part.
11. Division two integers without using Multiplication and Division
a)->https://www.youtube.com/watch?v=m4L_5qG4vG8
O(Logn^2)
public int divide(int dividend, int divisor) {
if(dividend==1<<31 && divisor==-1)
return Integer.MAX_VALUE;
boolean sign=(dividend>=0)==(divisor>=0)?true:false;
dividend=Math.abs(dividend);
divisor=Math.abs(divisor);
int res=0;
while(dividend-divisor>=0){
int count=0;
while(dividend-(divisor<<1<<count)>=0){
count++;
}
res+=1<<count;
dividend-=divisor<<count;
}
return sign?res:-res;
}
b)->https://www.youtube.com/watch?v=bdxJHWIyyqI
O(Logn)
public static long divide(long dividend, long divisor)
{
long sign = ((dividend < 0) ^
(divisor < 0)) ? -1 : 1;
dividend = Math.abs(dividend);
divisor = Math.abs(divisor);
long quotient = 0, temp = 0;
for (int i = 31; i >= 0; --i)
{
if (temp + (divisor << i) <= dividend)
{
temp += divisor << i;
quotient |= 1L << i;
}
}
return (sign * quotient);
}
----------------------------------------------------------------------------------------------
12. Find position of the only set bit
Hint: Every number which is a power of two has only one set bit.
static int findPosition(int n) {
if((n&(n-1))!=0||n==0)
return -1;
int count=0;
while(n!=0){
n=n>>1;
count++;
}
return count;
}
----------------------------------------------------------------------------------------------
13.
A)O(LogN) -> just do this method int interview
if N is odd-> 2x+1; N^2->4x^2+4x+1;
if N is even->2x; N^2->4x^2
static int square(int n)
{
// Base case
if (n == 0)
return 0;
// Handle negative number
if (n < 0)
n = -n;
// Get floor(n/2) using
// right shift
int x = n >> 1;
// If n is odd
;
if (n % 2 != 0)
return ((square(x) << 2) + (x << 2) + 1);
else // If n is even
return (square(x) << 2);
}
B)O(LogN)
public static int square(int num)
{
// Handle negative input
if (num < 0)
num = -num;
// Initialize result
int result = 0, times = num;
while (times > 0)
{
int possibleShifts = 0,
currTimes = 1;
while ((currTimes << 1) <= times)
{
currTimes = currTimes << 1;
++possibleShifts;
}
result = result + (num << possibleShifts);
times = times - currTimes;
}
return result;
}
----------------------------------------------------------------------------------------------
14. Power Set-> just like subset of string
public List<String> AllPossibleStrings(String s)
{
List<String>ans=new ArrayList<>();
int end=1<<s.length();
for(int i=1;i<end;i++){
int j=0;
int temp=i;
StringBuilder sb=new StringBuilder();
while(temp!=0){
int lastbit=temp&1;
if(lastbit==1){
sb.append(s.charAt(j));
}
j++;
temp=temp>>1;
}
ans.add(sb.toString());
}
Collections.sort(ans);
return ans;
}
----------------------------------------------------------------------------------------------
15.