字符串转整数及回文判断
Posted toney-01-22
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字符串转整数及回文判断相关的知识,希望对你有一定的参考价值。
一、字符串转整数
以“123456”为例
#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 ", result); return 0; } int str_to_int(char const *src) { int ret = 0; if (NULL == src) { return ret; } while (‘ ‘ != *src) { int tem = *src - ‘0‘; ret = ret * 10 + tem; ++src; } return ret; }
完善后:
#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 ", 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; }
二、回文判断
从两边向中间
#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 "); } else { printf("Is‘not PALINDROME "); } 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; }
从中间到两边
#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 "); } else { printf("Is‘not PALINDROME "); } 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; }
以上是关于字符串转整数及回文判断的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 9. 回文数 [Palindrome Number (Easy)]