summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMistivia <i@mistivia.com>2025-10-13 18:57:19 +0800
committerMistivia <i@mistivia.com>2025-10-13 18:57:19 +0800
commitac1cbcd4e36832381f687082fac1d487983bae07 (patch)
tree782676a152122ad4876d4b6a916feec3b6e2833f
parentb298f6a131b6412cdecba6317dc00e6ef5f46aca (diff)
solve 8
-rw-r--r--0008/main.c58
1 files changed, 58 insertions, 0 deletions
diff --git a/0008/main.c b/0008/main.c
new file mode 100644
index 0000000..c229dd7
--- /dev/null
+++ b/0008/main.c
@@ -0,0 +1,58 @@
+#include <ctype.h>
+#include <stdint.h>
+#include <stdio.h>
+
+char * skip_space(char *s) {
+ while (isspace(*s)) s++;
+ return s;
+}
+
+int symbol(char **ps) {
+ char *s = *ps;
+ if (*s == '+') {
+ s++;
+ *ps = s;
+ return 1;
+ }
+ if (*s == '-') {
+ s++;
+ *ps = s;
+ return -1;
+ }
+ return 1;
+}
+
+int64_t read_num(char *s) {
+ int64_t r = 0;
+ int i = 0;
+ while (1) {
+ if (s[i] < '0' || s[i] > '9') {
+ return r;
+ }
+ r = r * 10 + s[i] - '0';
+ if (r > ((int64_t)1 << 32)) {
+ return r;
+ }
+ i++;
+ }
+ return r;
+}
+
+int myAtoi(char* s) {
+ s = skip_space(s);
+ int sym = symbol(&s);
+ int64_t r = read_num(s);
+ if (sym > 0) {
+ if (r > 2147483647) r = 2147483647;
+ } else {
+ if (r > 2147483648) r = 2147483648;
+ }
+ return sym > 0 ? r : -r;
+}
+
+int main() {
+ printf("%d\n", myAtoi("123"));
+ printf("%d\n", myAtoi(" +123"));
+ printf("%d\n", myAtoi("0000000000012345678"));
+ printf("%d\n", myAtoi("-123111111111111111"));
+} \ No newline at end of file