LeetCode-Atoi, leetcode

Source: Internet
Author: User

LeetCode-Atoi, leetcode

Implement atoi to convert a string to an integer.

There are already many solutions available on the Internet.

Here we mainly pay attention to some points (the most important thing is that the returned value should be assigned a value of long at the beginning because it may cross the border)

Then there are some special situations for analysis.

Class Solution {public: int atoi (string str) {if (str. length () = 0) {return 0;} long retVal = 0; int length = str. length (); int I = 0; char signFlag = 1; while (str [I] = '') {I ++ ;} if (str [I] = '-') {I ++; signFlag =-1;} else if (str [I] = '+ ') {I ++ ;}for (; I <length; I ++) {int n = str [I]-'0'; if (n <0) | (n> 9) {return retVal * signFlag; // <special symbol displayed} retVal = retVal * 10 + n; if (retVal * signFlag> INT_MAX) {return INT_MAX;} else if (retVal * signFlag <INT_MIN) {return INT_MIN ;}} return retVal * signFlag ;}};


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.