Convert a string to an integer

© Parineeth M R

Question 25. Convert a string to an integer without using built-in functions


The function for converting a string to an integer is given below:

C/C++


/*
str: string to be converted to an integer
Result: integer value of the string
*/
int function_atoi(const char * str)
{
	int i, length; 
	int val = 0;
	int is_negative = 0;

	if (!str)
		return 0;

	length = strlen(str);
	i = 0;
	if (str[0] == '-') {
		is_negative = 1;
		++i;
	} 

	while (i < length ) {
		if (str[i] >= '0' && str[i] <= '9') {
			val = (val * 10) + (str[i] - '0');
		}
		else {
			break;
		}
		++i;
	}
	
	if (is_negative)
		val = -1 * val;

	return val;
}



Java


/*
str1: string to be converted to integer
result: integer value of string
*/
public static int strToInt(char[] str1) {
	int result = 0;
	boolean isNegative = false;
	int count = 0;
	
	for (char c : str1) {
		if (c == '-' && count == 0)
			isNegative = true;
		
		if ('0' <= c && c <= '9') 
			result = (result * 10) + (c - '0');

		count++; 
	}

	if (isNegative)
		result = -1 * result;

	return result;
}



Python


#str1: string to be converted to integer
#result: integer value of string
def str_to_int(str1):
	result = 0
	count = 0
	is_negative = False

	for c in str1:
		if (c == '-' and count == 0):
			is_negative = True

		if ('0' <= c and c <= '9'):
			result = (result * 10) + (ord(c) - ord('0'))

		count += 1

	if (is_negative):
		result = -1 * result 
		
	return result