Merge pull request #327 from SaurusXI/master

Solution to leetcode Problem 190 and 191
This commit is contained in:
Hai Hoang Dang
2019-10-04 06:40:00 -07:00
committed by GitHub
3 changed files with 25 additions and 0 deletions

View File

@@ -31,6 +31,8 @@ LeetCode
|160|[Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/) | [C](./src/160.c)|Easy|
|169|[Majority Element](https://leetcode.com/problems/majority-element/) | [C](./src/169.c)|Easy|
|173|[Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [C](./src/173.c)|Medium|
|190|[Reverse Bits](https://leetcode.com/problems/reverse-bits/) | [C](./src/190.c)|Easy|
|191|[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [C](./src/191.c)|Easy|
|203|[Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/) | [C](./src/203.c)|Easy|
|206|[Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [C](./src/206.c)|Easy|
|215|[Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C](./src/215.c)|Medium|

13
leetcode/src/190.c Normal file
View File

@@ -0,0 +1,13 @@
uint32_t reverseBits(uint32_t n) {
uint TotalBits = 32;
uint32_t reverse_int = 0; //stored in memory as 32 bits, each bit valued 0
uint i;
for(i = 0; i < TotalBits; i++) {
if((n & (UINT32_C(1) << i))) //if the bit on the ith position of 32 bit input is 1, then proceed
//Further note the use of UINT32_C to convert 1 to unsigned 32 bit int, since just 1 is treated as int which cannot be shifted left more than 30 times
reverse_int = reverse_int | (UINT32_C(1) << (TotalBits - 1 - i)); //Convert the ith bit from the end in reverse_int from 0 to 1, if ith bit from beginning in n is 1
//This is achieved by using bitwise OR on reverse_int (where ith bit from end is currently 0) and
//1 shifted left 31 - i bits (to ith bit from the end)
}
return reverse_int;
}

10
leetcode/src/191.c Normal file
View File

@@ -0,0 +1,10 @@
int hammingWeight(uint32_t n) {
int TotalBits = 32;
int i, weight = 0;
for(i = 0; i < TotalBits; i++) {
if(n & (UINT32_C(1) << i)) //if the bit on the ith position of 32 bit input is 1, then proceed
//Further note the use of UINT32_C to convert 1 to unsigned 32 bit int, as just 1 is treated as int which cannot be shifted left more than 30 times
weight += 1;
}
return weight;
}