diff --git "a/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/README.md" index ebe212c8fb7b0..1edfd50f307a8 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/README.md" @@ -143,6 +143,46 @@ class Solution { } ``` +#### C++ + +```cpp +class Solution { +public: + int strToInt(string str) { + int res = 0, bndry = INT_MAX / 10; + int i = 0, sign = 1, length = str.size(); + if (length == 0) { + return 0; + } + // 删除首部空格 + while (str[i] == ' ') { + if (++i == length) { + return 0; + } + } + // 若有负号则标识符号位 + if (str[i] == '-') { + sign = -1; + } + if (str[i] == '-' || str[i] == '+') { + i++; + } + for (int j = i; j < length; j++) { + if (str[j] < '0' || str[j] > '9') { + break; + } + // res>214748364越界;res=214748364且str[j] > '7'越界 + if (res > bndry || res == bndry && str[j] > '7') { + return sign == 1 ? INT_MAX : INT_MIN; + } + // 从左向右遍历数字并更新结果 + res = res * 10 + (str[j] - '0'); + } + return sign * res; + } +}; +``` + #### Go ```go diff --git "a/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.cpp" new file mode 100644 index 0000000000000..c392b7ddcbd1f --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/Solution.cpp" @@ -0,0 +1,35 @@ +class Solution { +public: + int strToInt(string str) { + int res = 0, bndry = INT_MAX / 10; + int i = 0, sign = 1, length = str.size(); + if (length == 0) { + return 0; + } + // 删除首部空格 + while (str[i] == ' ') { + if (++i == length) { + return 0; + } + } + // 若有负号则标识符号位 + if (str[i] == '-') { + sign = -1; + } + if (str[i] == '-' || str[i] == '+') { + i++; + } + for (int j = i; j < length; j++) { + if (str[j] < '0' || str[j] > '9') { + break; + } + // res>214748364越界;res=214748364且str[j] > '7'越界 + if (res > bndry || res == bndry && str[j] > '7') { + return sign == 1 ? INT_MAX : INT_MIN; + } + // 从左向右遍历数字并更新结果 + res = res * 10 + (str[j] - '0'); + } + return sign * res; + } +};