[Leetcode-easy] String to Integer (atoi), leetcode-easyatoi

Source: Internet
Author: User

[Leetcode-easy] String to Integer (atoi), leetcode-easyatoi

Requirement: String> integer

* 1. First, discard the space before the string.
* 2. Then there may be positive and negative signs (note that only one is taken. If there are multiple positive and negative signs, this string cannot be converted and 0 is returned. For example, there is a "+-2" in the test case ").
* 3. The string can contain 0 ~ If a non-numeric character is encountered, only the part before the character is taken. For example, "-00123a66" is returned as "-123 ".
* 4. If the value exceeds the int range, the boundary value (2147483647 or-2147483648) is returned ).

Train of Thought: sequential reading and sequential processing. Positive number, result = result * 10 + digit; negative number: result = reuslt * 10-digit

1 public int myAtoi (String str) {2 if (str = null | str. length () = 0) return 0; 3 str = str. trim (); 4 5 boolean negative = false; 6 int I = 0; 7 if (str. charAt (I) = '+') {8 I ++; 9} else if (str. charAt (I) = '-') {10 negative = true; 11 I ++; 12} 13 double result = 0; // you must use double first, otherwise, it will first cross-border 14 for (; I <str. length (); I ++) {15 int digit = str. charAt (I)-'0'; 16 if (digit <0 | digit> 9) break; 17 if (negative = false) {18 result = result * 10 + digit; 19 if (result> Integer. MAX_VALUE) {20 return Integer. MAX_VALUE; 21} 22} else {23 result = result * 10-digit; 24 if (result <Integer. MIN_VALUE) {25 return Integer. MIN_VALUE; 26} 27} 28} 29 return (int) result; 30}

 

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.