Skip to content

Commit

Permalink
finish chapter 3
Browse files Browse the repository at this point in the history
  • Loading branch information
jlzhjp committed Dec 12, 2024
1 parent f4c6a23 commit b3b535d
Show file tree
Hide file tree
Showing 3 changed files with 140 additions and 0 deletions.
42 changes: 42 additions & 0 deletions chapter_3/exercise_3_04.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void reverse(char s[]);
void itoa(int n, char s[]);

int main()
{
char s[32];
itoa(INT_MIN, s);
printf("%s\n", s);
itoa(72, s);
printf("%s\n", s);

return 0;
}

void reverse(char s[])
{
int c;
for (int i = 0, j = strlen(s) - 1; i < j; ++i, --j) {
c = s[i], s[i] = s[j], s[j] = c;
}
}

void itoa(int n, char s[])
{
int sign = n;
int i = 0;
// at least one character must be installed in the array
do {
s[i++] = abs(n % 10) + '0';
} while ((n /= 10) != 0);

if (sign < 0)
s[i++] = '-';

s[i] = '\0';
reverse(s);
}
52 changes: 52 additions & 0 deletions chapter_3/exercise_3_05.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char int2char(int n);
void itob(int n, char s[], int b);
void reverse(char s[]);

int main()
{
int x = 255;
char s[32];
itob(x, s, 16);
printf("%s", s);

return 0;
}

void reverse(char s[])
{
int c;
for (int i = 0, j = strlen(s) - 1; i < j; ++i, --j) {
c = s[i], s[i] = s[j], s[j] = c;
}
}

void itob(int n, char s[], int b)
{
if (b < 2 || b > 36) {
fprintf(stderr, "unsupported base %d", b);
exit(1);
}

int sign = n;
int i = 0;
// at least one character must be installed in the array
do {
s[i++] = int2char(abs(n % b));
} while ((n /= b) != 0);

if (sign < 0)
s[i++] = '-';

s[i] = '\0';
reverse(s);
}

char int2char(int n)
{
if (0 <= n && n <= 9) return n + '0';
return 'A' + n - 10;
}
46 changes: 46 additions & 0 deletions chapter_3/exercise_3_06.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void reverse(char s[]);
void itoa(int n, char s[], int minwidth);

int main()
{
char s[32];
itoa(INT_MIN, s, 12);
printf("%s\n", s);
itoa(72, s, 12);
printf("%s\n", s);

return 0;
}

void reverse(char s[])
{
int c;
for (int i = 0, j = strlen(s) - 1; i < j; ++i, --j) {
c = s[i], s[i] = s[j], s[j] = c;
}
}

void itoa(int n, char s[], int minwidth)
{
int sign = n;
int i = 0;
// at least one character must be installed in the array
do {
s[i++] = abs(n % 10) + '0';
} while ((n /= 10) != 0);

if (sign < 0)
s[i++] = '-';

while (i < minwidth) {
s[i++] = ' ';
}

s[i] = '\0';
reverse(s);
}

0 comments on commit b3b535d

Please sign in to comment.