[One Question of the Day] Convert a string to an integer

Source title
cattle off network
links: convert a string to an integer

Title description To
convert a string to an integer, it is required that the library function that converts a string to an integer cannot be used. If the value is 0 or the string is not a valid value, 0 is returned.

Enter a description:

Enter a string, including alphanumeric characters, can be empty

Output description:

If it is a legal numeric expression, return the number, otherwise return 0

enter:

+2147483647
1a33

Output:

2147483647
0

Problem-solving ideas
Use the result of the previous calculation *10 for each calculation, which is equivalent to decimal carry, and then add the value of the current bit.
For example: the result of "123" conversion is
sum = 0
sum * 10+1->1
sum * 10+2->12
sum * 10+3->123

Note: The key to this question is to deal with several key boundary conditions:

  1. Empty string
  2. Sign handling
  3. Illegal characters in number string

Code display

class Solution
{
    
    
	public:
		int StrToInt(string str)
		{
    
    
			if(str.empty())
				return 0;
			int symbol = 1;
			if(str[0] == '-')//处理负号
			{
    
    
				symbol = -1;
				str[0] = '0';
			}
			else if(str[0] == '+')//处理正号
			{
    
    
				symbol = 1;
				str[0] = '0';
			}
			int sum = 0;
			for(int i = 0;i < str.size();++i)
			{
    
    
				if(str[i] < '0' || str[i] > '9')
				{
    
    
					sum = 0;
					break;
				}
				sum = sum * 10 + str[i] - '0';
			}
			return symbol * sum;
		}
};

Guess you like

Origin blog.csdn.net/zhao_leilei/article/details/110425790