Skip to content

Commit

Permalink
added bitwise operators
Browse files Browse the repository at this point in the history
  • Loading branch information
joeyouss committed Jun 5, 2021
1 parent 1bbc6be commit 3a3e331
Show file tree
Hide file tree
Showing 6 changed files with 61 additions and 16 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ This repository contains notes and starter code for Bit manipulation and mathema
## Topics to be covered :

View the list at -> https://docs.google.com/document/d/1W0GUTM3uBY2wt5pu1eRxmHKytSndcFpVoxdujh0gdhs/edit?usp=sharing
Bit manipulation -

### Bit manipulation -

1. Converting a number to binary
2. Bitwise operators introduction
Expand All @@ -14,7 +15,7 @@ Bit manipulation -
5. Find the number occuring odd number of times
6. Position of first right bit

Mathematics -
#### Mathematics -

1. Euclidean algorithm (GCD)
2. LCM
Expand Down
44 changes: 30 additions & 14 deletions bitmanipulation.cpp
Original file line number Diff line number Diff line change
@@ -1,20 +1,36 @@
#include<bits/stdc++.h>
using namespace std;
int main(){
// count set bits in every number from 1 to n
// brian kernighan algortihm
// n = 10 -> 1010 -> 2 set bits
// n-1 = 9 -> 1001
// n-1 = 8 -> 1000
// n= 16 -> 10000
// n-1 -> 01111 -> 15
// n-1 -> 14 -> 01110
// 10&9 -> 1000 -> 1 set bit
// n=n&(n-1) -> 8&7 -> 0000 > 0 set bit
// n&(n-1) -> it loses one rightmost bit at a time
while(n){
n = n&(n-1);
count++;
int n = 10;
// 168421
// 16+1 -> 10001
// 10-> 1010
int binary[10];
int i = 0;
// n = 10
while(n>0){
// binary[0] = 0
// binary[1] = 1
// binary[2] = 0
// binary[3]= 1
// 0101
binary[i] = n%2;
// 10-> 5
// 5/2 -> 2
n=n/2;
// i=1
// i=2
i++;
}
// 17/2 -> 1
// 8/2 -> 0
// 4/2 ->0
// 2/2-> 0
// 1/2 -> 1

// dry run for 10
for(int k = i-1;k>=0;k--){
cout<<binary[k];
}
return 0;
}
Binary file modified bitmanipulation.exe
Binary file not shown.
28 changes: 28 additions & 0 deletions bitwise.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#include<bits/stdc++.h>
using namespace std;
int main(){
cout<<sizeof(int)<<endl;
// 4 bytes -> 32 bits
// a-> 0101
int a = 5;
// b-> 1001
int b = 9;
// 6 bitwise operators
// a&b -> 0001 ->1
cout<<(a&b)<<endl;
// a|b-> 1101 ->13
cout<<(a|b)<<endl;
// 1100 -> 12
cout<<(a^b)<<endl;
// 01001 -> 10010 -> 18
cout<<(b<<1)<<endl;
// 1001-> 0100 -> 4
cout<<(b>>1)<<endl;
// a -> 0(28).....0101 -> 1(28)...1010 -> 8+2 = 10
// whenever there is a 1 present at the first index -> it is a negative number
// 2s complement = 1s complement + 1
// 0(28)...0101 = 0101+1 = 0110 -> 6
// -6
cout<<(~a)<<endl;

}
Binary file added bitwise.exe
Binary file not shown.
Binary file added sieve.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 3a3e331

Please sign in to comment.