一、字符串转整数

以“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\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;
}

完善后:

#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;
}

 

二、回文判断

从两边向中间

#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;
}

 从中间到两边

#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;
}