Topic Description:
Converts a string to an integer that requires a library function that cannot convert integers using a string.
Input:
The input may contain more than one test sample.
For each test case, enter a legal or illegal string representing an integer n (1<= n<=10000000).
Output:
corresponding to each test case,
If you enter a valid string (that is, an integer), output the integer.
If entered as an illegal string, the output is "my God."
Sample input: 5-5+8 sample output: 5-58 on this topic, the title itself is good, the real core of the code is so two lines, most of the code is basically doing illegal input inspection.
Recently do these several questions, to nine degrees backstage test case is a little bit silent, the test case of this topic should have the problem, I write the code to test a lot of different illegal input and the legal input, have no problem, but on nine degrees OJ only fourth Test case through, the other four all WA, I've been doing this all night. , then the other people AC code, to test, the result of all kinds of illegal input are not processed, a lot of illegal input, get a variety of answers.
First put the code, you help me to see the wood has not considered the place:
#include <stdio.h> #include <stdbool.h> bool IsValid;
Long Strtoiint (const char *STR) {//illegal input if (str = NULL) {IsValid = false;
return 0;
}//is a negative number bool Isminus = FALSE;
Skip the front whitespace character while (*str = = ") str++;
The first non-white-space character is + number if (*str = = ' + ') str++;
The first non-white-space character is-number else if (*str = = ") {str++;
Isminus = true;
//If only a blank character, symbol bit, or nothing is entered, illegal input if (*str = = ' ") {IsValid = false;
return 0; If the input is valid, it is converted to an integer long num = 0;
The result of converting to an integer//so that the input similar to 234ASD can be determined as legitimate input, resulting in 234 while (*str!= ' ") {//input is not between 0-9, illegal input
if (*str< ' 0 ' | | | | *str> ' 9 ') {IsValid = false;
return 0; Convert num = 10*num + (*str-' 0 ') to a valid input without a sign bit
str++; ////Convert positive num to symbol bit = Isminus?
( -1*num): num;
Determine if the scope of the int has been overrun if (Num>0x7fffffff | | num< (signed int) 0X80000000) {IsValid = false;
return 0;
There is no return on//above, it does not occur that the overflow returns NUM is valid;
int main () {static char str[100000000];
while (gets (str)!= NULL) {IsValid = true;
Long result = Strtoiint (str);
if (IsValid) printf ("%ld\n", result);
else printf ("My god\n");
return 0; }
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/