Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
begeekmyfriend committed Nov 27, 2017
2 parents 76bb9cb + 621e77c commit ca2e846
Show file tree
Hide file tree
Showing 6 changed files with 105 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 189_rotate_array/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test rotate_array.c
49 changes: 49 additions & 0 deletions 189_rotate_array/rotate_array.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#include <stdio.h>
#include <stdlib.h>

static void reverse(int *nums, int lo, int hi)
{
while (lo < hi) {
int tmp = nums[lo];
nums[lo] = nums[hi];
nums[hi] = tmp;
lo++;
hi--;
}
}

static void rotate(int* nums, int numsSize, int k)
{
k %= numsSize;
if (k == 0) {
return;
}

reverse(nums, 0, numsSize - 1 - k);
reverse(nums, numsSize - k, numsSize - 1);
reverse(nums, 0, numsSize - 1);
}

int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: ./test k n1 n2...\n");
exit(-1);
}

int k = atoi(argv[1]);
int i, count = argc - 2;
int *nums = malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
nums[i] = atoi(argv[i + 2]);
}

rotate(nums, count, k);

for (i = 0; i < count; i++) {
printf("%d ", nums[i]);
}
printf("\n");

return 0;
}
2 changes: 2 additions & 0 deletions 190_reverse_bits/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test reverse_bits.c
26 changes: 26 additions & 0 deletions 190_reverse_bits/reverse_bits.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

static uint32_t reverseBits(uint32_t n)
{
int i;
uint32_t res = 0;
for (i = 0; i < 32; i++) {
res <<= 1;
res |= n & 0x1;
n >>= 1;
}
return res;
}

int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: ./test n\n");
exit(-1);
}

printf("%u\n", reverseBits(atoi(argv[1])));
return 0;
}
2 changes: 2 additions & 0 deletions 191_number_of_one_bits/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test hamming_weight.c
24 changes: 24 additions & 0 deletions 191_number_of_one_bits/hamming_weight.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

static int hammingWeight(uint32_t n)
{
int count = 0;
while (n > 0) {
n = n & (n - 1);
count++;
}
return count;
}

int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: ./test n\n");
exit(-1);
}

printf("%d\n", hammingWeight(atoi(argv[1])));
return 0;
}

0 comments on commit ca2e846

Please sign in to comment.