aboutsummaryrefslogtreecommitdiff
path: root/challenge-084
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2020-10-27 12:39:00 +0100
committerAbigail <abigail@abigail.be>2020-10-27 12:39:00 +0100
commit5c79da5bcabef66e1eb1e5c3aa52edb6e3d39888 (patch)
tree479eeb5dc462ea3cd242dae3c86853807fa9d096 /challenge-084
parent27806ae91adb65d8d4f0f494ac5f3de5bd459739 (diff)
downloadperlweeklychallenge-club-5c79da5bcabef66e1eb1e5c3aa52edb6e3d39888.tar.gz
perlweeklychallenge-club-5c79da5bcabef66e1eb1e5c3aa52edb6e3d39888.tar.bz2
perlweeklychallenge-club-5c79da5bcabef66e1eb1e5c3aa52edb6e3d39888.zip
C solution for week 84/part 1.
Diffstat (limited to 'challenge-084')
-rw-r--r--challenge-084/abigail/c/ch-1.c51
1 files changed, 51 insertions, 0 deletions
diff --git a/challenge-084/abigail/c/ch-1.c b/challenge-084/abigail/c/ch-1.c
new file mode 100644
index 0000000000..6fabe087ac
--- /dev/null
+++ b/challenge-084/abigail/c/ch-1.c
@@ -0,0 +1,51 @@
+# include <stdlib.h>
+# include <stdio.h>
+# include <errno.h>
+
+
+int main (void) {
+ char *line = NULL;
+ size_t len = 0;
+ ssize_t length = 0;
+ long result;
+ /*
+ * Iterate over the input, reading one line at a time
+ */
+ while ((length = getline (&line, &len, stdin)) != -1) {
+ /*
+ * Chop off any newline
+ */
+ if (line [length - 1] == '\n') {
+ line [length - 1] = '\0';
+ length --;
+ }
+ /*
+ * Reverse the digits; we need to skip any leading hyphen.
+ */
+ ssize_t i = 0;
+ if (line [0] == '-') {
+ i = 1;
+ }
+ ssize_t j = length - 1;
+ for (;i < j; i ++, j --) {
+ char t = line [i];
+ line [i] = line [j];
+ line [j] = t;
+ }
+ /*
+ * Check whether the result fits in a 32-bit integer.
+ * We first convert the string to a long. If we get
+ * an overflow or underflow, we can't fit anyway.
+ * Otherwise, we compare the result with the bounds.
+ */
+ errno = 0;
+ result = strtol (line, NULL, 10);
+ if (errno == ERANGE || result > 2147483647 || result < -2147483648) {
+ printf ("0\n");
+ }
+ else {
+ printf ("%s\n", line);
+ }
+ }
+ free (line);
+}