[Programmer interview questions selected 100 questions] 17. Converts a string to an integer, a programmer's integer
Question
Enter a string that represents an integer, convert it to an integer, and output it. For example, if the input string is "345", an integer of 345 is output.
Analysis
Although this question is not very difficult, the basic functions of C/C ++ language can be achieved, but the code written by different programmers for this question is very different, it can be said that this question can reflect the thinking and programming habits of programmers, so it has been used as an interview question by many companies, including Microsoft. It is recommended that you write the code before reading it, and then compare the differences between the code you write and the reference code below.
We need to consider the following issues:
(1) Positive and negative issues:
An integer may not only contain numbers, but may also start with '+' or '-' to indicate positive and negative integers. Therefore, we need to perform special processing on the first character of this string.
If the first character is '+', no operation is required;
If the first character is '-', it indicates that this integer is a negative number. At the end, we need to convert the obtained value to a negative number.
(2) invalid characters:
The input string may contain characters that are not numbers. Every time we encounter these invalid characters, we do not need to continue the conversion.
(3) overflow:
Because the input number is input in the form of a string, it is possible that after a large number is converted, it will exceed the maximum integer that can be expressed and overflow.
Code
/* ------------------------------------------- * Date: * Author: SJF0115 * Title: 17. convert the string to an integer * Source: programmer selection 100 Topic * blog: ------------------------------------------- */# include <iostream> # include <climits> using namespace std; class Solution {public: bool StrToInt (string str, int & num) {int size = str. size (); if (size <= 0) {return false;} // if // positive and Negative int index = 0; bool positive = true; if (str [index] = '-'){ Positive = false; ++ index;} // if else if (str [index] = '+') {++ index;} // else long result = 0; for (int I = index; I <size; ++ I) {// determine whether the character is invalid if (str [I] <'0' | str [I]> '9') {cout <"invalid character" <endl; return false;} // if result = result * 10 + str [I]-'0'; // determine whether the overflow exists if (result> INT_MAX) {cout <"overflow" <endl; return false;} // if} // for num = positive = false? (-1 * result): result; return true ;}; int main () {Solution solution; string str ("-122222222222222"); int num = 0; if (solution. strToInt (str, num) {cout <num <endl ;}// if else {cout <"conversion problem" <endl ;}}