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.
First, we will analyze how to complete the basic function, that is, how to convert the string representing an integer into an integer correctly. Or take "345" as an example. When we scan the string's first character '3', we do not know how many digits are behind it. We only know that this is the first character, so the number we get at this time is 3. When the second digit '4' is scanned, we now know that the first digit is 3, and a Number 4 is added to the end. The first digit 3 is 30, the resulting number is 3*10 + 4 = 34. Then we scanned the character '5' again. We already know that there are 34 in front of '5'. Because we need to add 5 in front, the 34 in front is equivalent to 340, the resulting number is 34*10 + 5 = 345.
From the analysis, we cannot come up with a conversion idea: every time a character is scanned, we multiply the previous number by 10 and add the number represented by the current character. This idea is not hard to achieve with loops.
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 '-', this integer is a negative number, in the end, we need to convert the obtained value to a negative number.
Next we try to handle illegal input. Since the pointer is input, the first thing we need to do before using the pointer is to judge whether the pointer is null. If you try to access a null pointer, the program will inevitably crash. In addition, 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. The last problem to consider is the overflow problem. 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.
Now the analysis is almost done, and you need to write the code. First, we should consider how to declare this function. Since the string is converted into an integer, we naturally think:
Int strtoint (const char * Str );
This statement seems no problem. But what value should I return when the input string is a null pointer or contains invalid characters? How about 0? So how can we distinguish between illegal input and the string itself being "0?
Next we will consider another idea. We can return a Boolean value to indicate whether the input is valid, and put the converted integer in the parameter list as a reference or pointer. Therefore, we can declare the following:
Bool strtoint (const char * STR, Int & num );
This approach solves the preceding problems. However, when using this function, the user of this function will not find it very convenient, because he cannot directly assign the obtained integer value to other shaping faces, which is not intuitive enough.
The first statement is intuitive. How can users be notified when illegal input is detected while the system is intuitive? One solution is to define a global variable, which is marked whenever an illegal input occurs. After calling this function, you can check the global variable to determine whether the conversion is successful.
The complete implementation code is written below. Reference code:
Enum status {kvalid = 0, kinvalid };
Int g_nstatus = kvalid;
//////////////////////////////////////// ///////////////////////////////
// Convert a string into an integer
//////////////////////////////////////// ///////////////////////////////
Int strtoint (const char * Str)
{
G_nstatus = kinvalid;
Long long num = 0;
If (STR! = NULL)
{
Const char * digit = STR;
// The first char in the string maybe '+' or '-'
Bool minus = false;
If (* digit = '+ ')
Digit ++;
Else if (* digit = '-')
{
Digit ++;
Minus = true;
}
// The remaining chars in the string
While (* digit! = '/0 ')
{
If (* digit> = '0' & * digit <= '9 ')
{
Num = num * 10 + (* digit-'0 ');
// Overflow
If (Num> STD: numeric_limits <int>: max ())
{
Num = 0;
Break;
}
Digit ++;
}
// If the char is not a digit, invalid input
Else
{
Num = 0;
Break;
}
}
If (* digit = '/0 ')
{
G_nstatus = kvalid;
If (minus)
Num = 0-num;
}
}
Return static_cast <int> (Num );
}
Discussion: In the reference code, I chose the first declaration method. However, during the interview, we can use any declaration method for implementation. However, when the interviewer asks us why we choose, we should evaluate the advantages and disadvantages of the two. The first declaration method is very intuitive for users, but it is not elegant enough to use global variables. The second method is to use the return value to indicate whether the input is legal. This method is used in many APIs, however, the function declared by this method is not intuitive enough.
Finally, it is worth mentioning that in the library functions provided by C language, function atoi can convert strings to integers. Its declaration is int atoi (const char * Str ). This function uses a global variable to indicate whether the input is valid.
Bytes ----------------------------------------------------------------------------------------------------
The C language provides several standard library functions that can convert numbers of any type (integer, long integer, floating point type, etc.) into strings. Here is an example of converting integers into strings using the ITOA () function:
# Include <stdio. h>
# Include <stdlib. h>
Void main (void)
{
Int num = 100;
Char STR [25];
ITOA (Num, STR, 10 );
Printf ("the number 'num' is % d and the string 'str' is % S./N ",
Num, STR );
}
The ITOA () function has three parameters: the first parameter is the number to be converted, and the second parameter is the target string to be written into the conversion result, the third parameter is the base number used when the number is transferred. In the preceding example, the conversion base is 10. 10: decimal; 2: Binary...
ITOA is not a standard C function. It is unique to Windows. If you want to write cross-platform programs, use sprintf.
It is extended on the Windows platform. The standard library contains sprintf, which is more powerful than this one. Its usage is similar to that of printf:
Char STR [255];
Sprintf (STR, "% x", 100); // convert 100 to a hexadecimal string.
The following functions can convert integers into strings:
----------------------------------------------------------
Function Name
----------------------------------------------------------
ITOA () converts an integer value to a string
ITOA () converts a long integer value to a string
Ultoa () converts an unsigned long integer value to a string
A atoi converts a string to an integer.
Example program:
# Include <ctype. h>
# Include <stdio. h>
Int atoi (char s []);
Int main (void)
{
Char s [100];
Gets (s );
Printf ("integer = % d/N", atoi (s ));
Return 0;
}
Int atoi (char s [])
{
Int I, n, sign;
For (I = 0; isspace (s [I]); I ++) // skip the blank space
;
Sign = (s [I] = '-')? -1:1;
If (s [I] = '+' | s [I] = '-') // skip the symbol
I ++;
For (n = 0; isdigit (s [I]); I ++)
N = 10 * n + (s [I]-'0'); // converts a number to an integer.
Return sign * N;
}
ITOA converts an integer to a string.
Example program:
# Include <ctype. h>
# Include <stdio. h>
Void ITOA (int n, char s []);
// Atoi function: Convert s to integer
Int main (void)
{
Int N;
Char s [100];
Printf ("input N:/N ");
Scanf ("% d", & N );
Printf ("the string:/N ");
ITOA (N, S );
Return 0;
}
Void ITOA (int n, char s [])
{
Int I, j, sign;
If (Sign = N) <0) // record symbol
N =-N; // convert n to positive I = 0;
Do {
S [I ++] = n % 10 + '0'; // obtain the next number
} While (n/= 10)> 0); // Delete the number
If (sign <0)
S [I ++] = '-';
S [I] = '/0 ';
For (j = I; j> = 0; j --) // The generated numbers are in reverse order.
Printf ("% C", s [J]);
}
Bytes ------------------------------------------------------------------------------------
Write your own atoi function ---- (NOTE: When the defined atoi function is the same as the atoi function in the database, throwing an exception will cause the exception to exit, I personally think that the exception is not unknown to be thrown by that function, so coredump)
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
# Include <unistd. h>
# Include <assert. h>
# Include <iostream>
# Include <string>
# Include <exception>
Using namespace STD;
Const unsigned int sign_bit = 0x1 <31;
Bool isdigit (const char ch)
{
If (CH <= '9' & ch> = '0 ')
{
Return true;
}
Return false;
}
Int atoi_ I (const char * Str)
{
Assert (STR! = NULL );
While (''= * Str) {STR ++ ;}
Int result = 0;
Bool signflag = false;
If ('+' = * Str)
{
If (false = isdigit (* ++ Str) throw "input format error! ";
}
Else if ('-' = * Str)
{
If (false = isdigit (* ++ Str) throw "input format error! ";
Signflag = true;
}
Else if (* STR> '9' | * STR <'0 ')
{
Throw "input format error! ";
}
Do
{
Result = Result * 10 + * STR ++-'0 ';
If (Result & sign_bit )! = 0)
{
Throw "overflow error! ";
}
}
While (isdigit (* Str ));
If (true = signflag)
{
Result =-result;
}
Return result;
}
Int main (INT argc, char * argv [])
{
Char input [1024];
While (1)
{
Try
{
Cout <"input array :";
Cin> input;
Printf ("Exchange: % d/N", atoi_ I (input ));
}
Catch (const char * P)
{
Cout <"error info:" <p <Endl;
}
Catch (...)
{
Cout <"test" <Endl;
}
}
Return 0;
}
Bytes -----------------------------------------------------------------------------------
ITOA function (Self)
# Define swap (x, y) (x) = (x) ^ (y); (y) = (x) ^ (y); (x) = (X) ^ (y)
Char * itoa_ I (INT SRC, char *)
{
Bool signflag = false;
If (SRC <0)
{
Src =-Src;
Signflag = true;
}
Int K = 0;
Do
{
A [k ++] = SRC % 10 + '0 ';
}
While (src/= 10)> 0 );
If (true = signflag)
{
A [k ++] = '-';
}
A [k] = '/0 ';
For (INT I = 0, j = k-1; I <j; ++ I, -- J)
{
Swap (* (a + I), * (a + j ));
}
Return;
}