Front end and algorithm leetcode 8. String to integer (atoi)

Keywords: Javascript Java github

[TOC]

Front end and algorithm leetcode 8. String to integer (atoi)

Title Description

Please implement an atoi function to convert strings to integers.

First, the function discards the useless start space characters as needed until the first non space character is found.

When the first non empty character we find is a positive or negative sign, we will combine the symbol with as many consecutive numbers as possible as the sign of the integer; if the first non empty character is a number, we will directly combine it with consecutive number characters to form an integer.

In addition to the valid integer part of the string, there may be extra characters, which can be ignored and should not affect the function.

Note: if the first non whitespace character in the string is not a valid integer character, the string is empty, or the string contains only whitespace characters, your function does not need to be converted.

In any case, return 0 if the function does not perform a valid conversion.

Explain:

Assuming that our environment can only store 32-bit signed integers, the value range is [− 231, − 231 − 1]. If the value is outside this range, return to − INT_MAX (231 − 1) or − INT_MIN (− 231).

Example 1:

Input: "42"
Output: 42

Example 2:

Enter: - 42
 Output: -42
 Explanation: the first non blank character is' - ', which is a minus sign.
We try to combine the minus sign with all the consecutive numbers that follow, and finally we get - 42.

Example 3:

Input: "4193 with words"
Output: 4193
 Explanation: the conversion ends with the number '3' because its next character is not a number.

Example 4:

Type: "words and 987"
Output: 0
 Explanation: the first non empty character is' w ', but it is not a number or a positive or negative sign.
     Therefore, a valid conversion cannot be performed.

Example 5:

Input: - 91283472332
 Output: - 2147483648
 Explanation: the number "- 91283472332" exceeds the range of 32-bit signed integers. 
Therefore, INT_MIN (− 231) is returned.

8. String to integer (atoi)

outline

Hand rub an api

Tips

loop

analysis

Solution 1: regular

The part of a string that is stripped of space and then regular matched with a number beginning with - +

Solution 2: api

Directly parseint, just judge it

Solution 2: hand rubbing an api

This method is much more universal. Clear the space and judge whether the first place is a number. First, implement js version to beat 80%, then implement 2ms on java to beat 99%

algorithm

java solution

class Solution {
    public int myAtoi(String str) {
      if(str.isEmpty()) return 0 ;
      char[] req = str.toCharArray();
      long res = 0;
      int i=0,s=1,n=str.length();
      while(i<n&&req[i]==' '){i++;}
      if(i<n && req[i]=='+'){i++;}
      else if(i<n&&req[i]=='-'){i++;s=-1;}
      while(i<n&&(req[i]>='0'&&req[i]<='9')){
        if(res!=(int)res){
          return (s==1)?Integer.MAX_VALUE:Integer.MIN_VALUE;
        }
        res=res*10+req[i++]-'0';
      }
      if(res!=(int)res){
        return (s==1)?Integer.MAX_VALUE:Integer.MIN_VALUE;
      }
      return (int)(res*s);
    }
}

js solution

/**
 * @param {string} str
 * @return {number}
 */
var myAtoi = function (str) {
  const result = str.trim().match(/^(-|\+)?\d+/g);
  return result? Math.max(Math.min(Number(result[0]), 2 ** 31 - 1), -(2 ** 31)): 0;
  // One line of code to solve the problem
  // return parseInt(str, 10) < -(2 ** 31) ? -(2 ** 31) : (parseInt(str, 10) > (2 ** 31) - 1 ? (2 ** 31) - 1 : ((parseInt(str, 10) >= -(2 ** 31) && parseInt(str, 10) <= (2 ** 31) - 1) ? parseInt(str, 10) : 0));
  // Serious api Xia solution
  // let result = parseInt(str, 10);
  // let max = 2 ** 31;
  // if (Number.isNaN(result)) {
  //   return 0;
  // } else if (result < 0 - max) {
  //   return 0 - max;
  // } else if (result > max - 1) {
  //   return max - 1;
  // } else {
  //   return result;
  // }
// The solution of untidy api
//   str = str.trim(); / / clear space
//   let max = 2 ** 31;
//   //If it's not a number
//   if (!(str.charCodeAt(0) >= 48 && str.charCodeAt(0) <= 57)) {
//     if (str.charAt(0) === '+') {
//       let req = res(str, 1);
//       return req >= (max - 1) ? max - 1 : req;
//     }
//     if (str.charAt(0) === '-') {
//       let req = -(res(str, 1));
//       return req <= -max ? -max : req;
//     }
//   } else {
//     //The first is the number
//     let req = res(str, 0);
//     return req >= (max - 1) ? max - 1 : req;
//   }
//   return 0;
// };
// //Parse number, first parameter string, second starting position
// const res = (s, num) => {
//   let r = 0;
//   for (let i = num; i < s.length; i++) {
//     //Accept numbers only
//     if (s.charCodeAt(i) <= 57 && s.charCodeAt(i) >= 48) {
//       r = r * 10 + (s.charCodeAt(i) - 48);
//     } else {
//       break;
//     }
//   }
//   //There is a gap between the maximum value and the minimum value. The judgment here is not as good as the judgment after the end
//   return r;
};

Run results of incoming test cases

input:
output:

results of enforcement

Execution time: 80 ms, beating 94.84% of users in all javascript submissions
 Memory consumption: 35.5 MB, beating 74.01% of users in all javascript submissions

GitHub warehouse

You can also give a star by checking github warehouse

View more

See more questions

Posted by mattfoster on Thu, 21 Nov 2019 07:26:16 -0800