No.008: String to Integer (atoi), no.008atoi

Source: Internet
Author: User

No.008: String to Integer (atoi), no.008atoi

Question:

Implement atoi to convert a string to an integer.
Hint:
Carefully consider all possible input cases.

Official difficulty:

Easy

Translation:

Implement the atoi algorithm to convert a string into an integer.

Tip: carefully consider various possible situations.

Additional information:

Atoi function is a function in the C language library. Baidu has implemented the following functions:

Requirements for atoi:
1. The function first discards as your whitespace characters as necessary until the first non-whitespace character is found.
Then, starting from this character, takes an optional initial plus or minus sign followed by as your numerical digits as possible,
And interprets them as a numerical value.
2. The string can contain additional characters after those that form the integral number,
Which are ignored and have no effect on the behavior of this function.
3. If the first sequence of non-whitespace characters in str is not a valid integral number,
Or if no such sequence exists because either str is empty or it contains only whitespace characters,
No conversion is saved med.
4. If no valid conversion cocould be specified med, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

Atoi function requirements:
1. Discard all blank strings until the first non-space string is encountered. Starting from the non-empty string, if the first one is "+" or "-", return as many numbers as possible.
2. A string can contain other characters after the previous integer. If it is ignored, it does not affect the function and ends the function immediately.
3. If the first non-null string is not an integer, or even the string is null or completely composed of a blank key, 0 is returned.
4. If the conversion fails, 0 is returned. If the conversion exceeds the maximum/minimum value of the integer, the Maximum/minimum value of the integer is returned.

Ideas:

1. Use the String. trim () method to remove spaces. Use the String. toCharArray () method to split the String into character arrays.

2. Consider the case where the length of the string to be removed from the space is 0.

3. Use a flag to record the first part of the array may be the operator "-" or "+", and then set the operator's position to 0 to facilitate subsequent assignment.

4. the maximum number of records starts to accumulate until a non-number exceeded the int value. sum is declared as long.

5. Special considerations beyond the scope.

Possible difficulties in solving problems:

1. When comparing or assigning values, always pay attention to the char type ''.

2. convert a char character number into a number to calculate array [I]-'0 '.

3. The relationship between Integer. MAX_VALUE and Integer. MIN_VALUE is not the opposite number.

Solution code:

1 private static int method (String str) {2 // enter space 3 char [] array = str. trim (). toCharArray (); 4 // 0 special processing 5 if (array. length = 0) {6 return 0; 7} 8 // positive/negative sign 9 int operatorFlag = 1; 10 // record return number, if long is exceeded, 11 long sum = 0 is not considered; 12 if (array [0] = '+' | array [0] = '-' | (array [0]> = '0' & array [0] <= '9 ')) {13 // set the operator to 0 to facilitate unified processing of 14 if (array [0] = '+') {15 // assign a value here, note that the char type 16 array [0] = '0'; 17 operatorFlag = 1; 18} else if (array [0] = '-') {19 array [0] = '0'; 20 operatorFlag =-1; 21} 22 // maximum bit 23 int maxLevel = 0; 24 // cyclically determine the highest bit of 25 for (int I = 0; I <array. length; I ++) {26 if (array [I]> = '0' & array [I] <= '9') {27 maxLevel ++; 28} else {29 // exit 30 break in case of a non-number; 31} 32} 33 // a copy of maxLevel is required to assign a value of 34 int copyMaxLevel = maxLevel; 35 // accumulate value, note that the subscript 36 for (int I = 0; I <maxLevel; I ++) {37 // pay attention to the char-type number, 38 sum + = (array [I]-'0') * Math. pow (10, -- copyMaxLevel); 39} 40 // processing out of range 41 long realNumber = sum * operatorFlag; 42 if (realNumber> Integer. MAX_VALUE) {43 return Integer. MAX_VALUE; 44} 45 if (realNumber <Integer. MIN_VALUE) {46 return Integer. MIN_VALUE; 47} 48 return (int) realNumber; 49} else {50 return 0; 51} 52}View Code

Test Code address:

Https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/easy/Q008.java

LeetCode address:

Https://leetcode.com/problems/string-to-integer-atoi/

PS: If you have any incorrect or more efficient methods, please leave a message. Thank you!

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.