Write a function that checks if the character is an integer, and if so, returns its integer value

Source: Internet
Author: User
Tags function prototype

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.