diff options
author | sinanmohd <pcmsinan@gmail.com> | 2022-06-15 12:34:06 +0530 |
---|---|---|
committer | sinanmohd <pcmsinan@gmail.com> | 2022-06-15 12:34:06 +0530 |
commit | f4dcb9e585d331c6bccccd42daedda18222ef672 (patch) | |
tree | 5d064b32221334a6f54af396444ca41964d86f62 | |
parent | fdd66ab773f88dcf31fc55b647d6d2de7f0647cf (diff) |
add 4.13.c
-rw-r--r-- | 4.13.c | 66 |
1 files changed, 66 insertions, 0 deletions
@@ -0,0 +1,66 @@ +#include <stdio.h> +#include <string.h> + +#define MAXLEN 15 + +void reverse(char str[], size_t left, size_t right); +char* itoa(int n, char str[]); +void swap(char array[], int i, int j); + +int +main(void) +{ + int n = 42069; + char str[MAXLEN]; + + printf("%d\n", n); + printf("%s\n", itoa(n, str)); + + return 0; +} + +void +reverse(char str[], size_t left, size_t right) +{ + if (left >= right) + return; + + swap(str, left, right); + reverse(str, left+1, right-1); +} + +char* +itoa(int n, char str[]) +{ + int sign, i; + + /* to include the most -ve int */ + n = ((sign = n) < 0) ? -(n+1) : n-1; + + i = 0; + do { + str[i++] = n%10 + '0'; + } while ((n /= 10) > 0); + + if (sign <0) + str[i++] = '-'; + + /* part of "to include the most -ve int" */ + str[0] += 1; + str[i] = '\0'; + + reverse(str, 0, strlen(str)-1); + + return str; +} + +void +swap(char array[], int i, int j) +{ + int temp; + + temp = array[i]; + + array[i] = array[j]; + array[j] = temp; +} |