Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Examples of bit manipulation in CPP #25

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions bit-manipulation/elementAppearingOnce.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/* Given an array of integers, every element appears twice except for one. Find that single one. */

#include <stdio.h>

int checkNum(int a[], int size) {
int ans = 0;
for(int i = 0; i < size; i++) {
ans^=a[i];
}
return ans;
}

int main() {
int arr[] = {1,1,2,2,3,4,4,5,5};

printf("Element appearing once is %d\n", checkNum(arr, sizeof(arr)/sizeof(arr[0])));
return 0;
}
23 changes: 23 additions & 0 deletions bit-manipulation/numberOfones.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/* Write a function that takes an unsigned integer and returns the number of 1 bits it has. */

#include <stdio.h>

int countOnes(int n) {
int ans = 0;
while(n) {
n = n&(n-1);
ans++;
}
return ans;
}

int main() {
printf("Enter a number you want to check the number of 1s in:\n");

int key;
scanf("%d", &key);

int ans = countOnes(key);
printf("%d\n", ans);
return 0;
}