1、字符串轉整數git
以「123456」爲例spa
#include <stdio.h> int str_to_int(char const *src); int main(int argc, char *argv[]) { char *src = "123456"; int result = 0; result = str_to_int(src); printf("%d\n", result); return 0; } int str_to_int(char const *src) { int ret = 0; if (NULL == src) { return ret; } while ('\0' != *src) { int tem = *src - '0'; ret = ret * 10 + tem; ++src; } return ret; }
完善後:blog
#include <stdio.h> #include <ctype.h> int str_to_int(char const *src); int main(int argc, char *argv[]) { char *src = "12345692329399"; int result = 0; result = str_to_int(src); printf("%d\n", result); return 0; } int str_to_int(char const *src) { static const int MAX_INT = (int)((unsigned)~0 >> 1); static const int MIN_INT = -(int)((unsigned)~0 >> 1) - 1; unsigned int n = 0; int sign = 1; if (NULL == src) { return n; } while (isspace(*src)) { ++src; } if ('+' == *src || '-' == *src) { if ('-' == *src) { sign = -1; } ++src; } //肯定是數字才進行循環 while (isdigit(*src)) { //處理溢出 int tem = *src - '0'; if (sign > 0 && (n > MAX_INT / 10 || (n == MAX_INT / 10 \ && tem > MAX_INT % 10))) { n = MAX_INT; break; } else if (sign < 0 && (n > (unsigned int)MIN_INT / 10 \ || (n == (unsigned int)MIN_INT /10 \ && tem > (unsigned int)MIN_INT % 10))) { n = MIN_INT; break; } n = n * 10 + tem; ++src; } return sign ? n : -n; }
2、迴文判斷字符串
從兩邊向中間string
#include <stdio.h> #include <string.h> int is_palindrome( char const *src, int n); int main(int argc, char *argv[]) { char *p_str = "12234321"; if (0 == is_palindrome(p_str, strlen(p_str))) { printf("THIS IS PALINDROME\n"); } else { printf("Is'not PALINDROME\n"); } return 0; } int is_palindrome( char const *src, int n) { if (NULL == src || n < 1) { return -1; } char const *front = NULL; char const *back = NULL; front = src; back = src + n - 1; while (front < back) { if (*front++ != *back--) { return -1; } } return 0; }
從中間到兩邊it
#include <stdio.h> #include <string.h> int is_palindrome( char const *src, int n); int main(int argc, char *argv[]) { char *p_str = "1234321"; if (0 == is_palindrome(p_str, strlen(p_str))) { printf("THIS IS PALINDROME\n"); } else { printf("Is'not PALINDROME\n"); } return 0; } int is_palindrome( char const *src, int n) { if (NULL == src || n < 1) { return -1; } int m = ((n >> 1) - 1) > 0 ? (n >> 1) - 1 : 0; char const *first = NULL; char const *second = NULL; first = src + m; second = src + n - 1 - m; while (first >= src) { if (*first-- != *second++) { return -1; } } return 0; }