Leetcode 8. String to Integer (atoi)

Source: Internet
Author: User

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Note:

1) prefix space

2) plus and minus signs

3) Overflow (long int can be used to prevent overflow)

1 int atoi (const char * str) 2 {3 int flag = 1; 4 int I = 0; 5 long int ret = 0; 6 7 if (NULL = str) 8 return 0; 9 while (str [I]! = '\ 0') & (str [I] = '') 10 I ++; 11 12 if (str [I] =' + ') 13 {14 flag = 1; 15 I ++; 16} 17 else if (str [I] = '-') 18 {19 flag =-1; 20 I ++; 21} 22 23 while (str [I]! = '\ 0') & (str [I]> = '0' & str [I] <= '9 ')) 24 {25 ret = ret * 10 + (str [I]-'0'); 26 if (flag = 1) & (ret * flag> INT_MAX )) 27 return INT_MAX; 28 if (flag =-1) & (ret * flag <INT_MIN) 29 return INT_MIN; 30 I ++; 31} 32 return (int) ret * flag; 33}

 

Leetcode 8. String to Integer (atoi)

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.