CPP] view Plaincopyprint? Write a function that checks if the character is an integer and, if so, returns its integer value. (or: How to write a function from string to Long integer with only 4 lines of code) #include "stdafx.h" #include <stdlib.h> #include <stdio.h> #include <string> #include <iostream> using Namespace std; Long strtoint (char *str,int length); int main (int argc, char* argv[]) {&nbs P int i=0; Char str[100]; while ((Str[i]=getchar ()) = ' 0 ') { i++; } long N=strtoint (str,i); cout<<n<<endl; return 0; } Long Strtoint (char *str,int length) { if (length > 1) { return str[0]== '-'? Strtoint (St R, Length-1) *10-(str[length-1]-' 0 '): Strtoint (str, length-1) *10+str[length-1]-' 0 '; } else { return str[0]== '-'? -1/10:str[0]-' 0 '; } }
Here is a description of the algorithm:
1. First consider some test cases: positive and negative cases, negative case is that the first character of the string must be considered '-', if not '-', mark the last one of the string, and then the previous string recursively. (In fact, recursion is completely unnecessary Ah, as long as the string can be scanned, the time complexity is 0 (n), this and the remainder of the 10, to be divisible by 10 after the number of the same method).
2. For coding, it is necessary to give a function prototype, to understand what the input is, what the output is, what can be changed, what needs to be applied in the function of the address space, and so on some of the details.
3. For a case where a string is converted to a positive number, it is generally necessary to take the contents of the corresponding bits in the string and subtract the 0 Ascaii: ' 0 ' can get their integer representation, which is common and must have such consciousness.