C code

C practice

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
#include <stdio.h>

int fib(int N);

int main() {
int res = fib(5);
printf("res is %d\n", res);
}

// approach 1
int fib(int N){
if (N <= 1) {
return N;
}
int lib[N + 1];
lib[0] = 0;
lib[1] = 1;
for (int i = 2; i <= N; i++) {
lib[i] = lib[i - 1] + lib[i - 2];
}
return lib[N];
}

// approach 2
int fib2(int N){
if (N <= 1)
return N;
return fib(N - 1) + fib(N - 2);
}
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
#include <stdio.h>
#include <math.h>
#include <ctype.h>

int myAtoi(char * str);

int main() {
int res = myAtoi(" 42 ");
printf("res is %d\n", res);
}

int myAtoi(char * str){
int i = 0, sign = 1;
while (str[i] == ' ') {
i += 1;
}

if (str[i] == '+')
i += 1;
else if (str[i] == '-') {
i += 1;
sign = -1;
}

long res = 0;
while (isdigit(str[i])) {
res = res * 10 + str[i] - '0';

if (sign * res >= pow(2, 31) - 1) {
return pow(2, 31) - 1;
} else if (sign * res <= pow(2,31) * (-1)) {
return pow(2, 31) * (-1);
}
i += 1;
}

return (int)res * sign;
}
  • 191. Number of 1 Bits bit operation
    1
    2
    3
    4
    5
    6
    7
    8
    int hammingWeight(uint32_t n) {
    int res = 0;
    while (n > 0) {
    res += n & 1;
    n = n >> 1;
    }
    return res;
    }
0%