String to INTEGER (atoi)

Source: Internet
Author: User

Problem: Convert the escape character to a number
Analysis: I think the question is not difficult, but there are many details, which are easy to think.
1. There is a space in front of the number, such as S = "123456"
2. there are unnecessary or more characters before the number, leading to a digital authentication error. The output value is 0, for example, S = "b1234", S = "++ 1233", and S = "+-1121"
3. There are unnecessary characters in the number. The number before the character is returned, for example, S = "12a12", S = "123 123"
4. The number is out of the range (-2147483648--2147483647). If the value of output-2147483648 exceeds the value of positive output 2147483647
In a knowledge point of science, if a certain number exceeds 2147483647, it will become a negative number, the opposite is the same

 

Class solution {public: int atoi (const char * Str) {long cur = 0; // initialization always forgets int num = 0, I = 0; int flag1 = 0, flag2 = 0; while (STR [I]! = '\ 0' & STR [I] = '') I ++; // discard if (STR [I] = '-') flag1 ++, I ++; else if (STR [I] = '+') flag2 ++, I ++; For (; STR [I]! = '\ 0'; I ++) {If (STR [I]> = '0' & STR [I] <= '9 ') {If (flag1 = 2) {cur = cur * 10-(STR [I]-'0'); // here is subtraction, because the cur symbol is a negative if (cur <-2147483648) Return-2147483648;} else if (flag1 = 1) cur =-str [I] + '0 ', flag1 ++; // record the negative number in the cur. else {cur = cur * 10 + (STR [I]-'0'); If (cur> 2147483647) return 2147483647 ;}} else break;} num = (INT) cur; return num ;}};

  

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.