字符串到整数的leetcode

时间:2019-11-19 07:13:01

标签: javascript data-structures

我正在关注leetcode问题

  

实现atoi,可将字符串转换为整数。

     

该函数首先丢弃必要的空白字符   直到找到第一个非空白字符。然后,从   此字符,后接可选的初始加号或减号   尽可能多的数字,并将它们解释为   数值。

     

字符串可以在构成字符串的字符之后包含其他字符。   整数,将被忽略并且对行为没有影响   

     

如果str中非空格字符的第一个序列不是   有效的整数,或者如果不存在这样的序列,因为   str为空或仅包含空格字符,不进行任何转换   被执行。

     

如果无法执行有效的转换,则返回零值。

     

注意:

     

仅空格字符''被视为空白字符。   假设我们正在处理一个只能存储的环境   32位带符号整数范围内的整数:[− 2 31 ,2 31 − 1]。如果   数值超出可表示的数值范围,   返回INT_MAX(2 31 − 1)或INT_MIN(−2 31 )。

问题链接:https://leetcode.com/problems/string-to-integer-atoi/

在此输入"-91283472332"时,我不确定他们为什么期望以下输出-2147483648而不是-91283472332

不确定,如果相关,但这是我的代码

/**
 * @param {string} str
 * @return {number}
 */
var myAtoi = function(str) {
    let i = 0
    let output = ''
    let nonWhiteCharacter = false 
    while (i<str.length) {
       const char = str[i]
       if (!char == " ") {
           if (char.toLowerCase() === char.toUpperCase()) {
            if (!nonWhiteCharacter) nonWhiteCharacter = true
               output = output + char
           }  
           if (!nonWhiteCharacter) return 0
       }
        i++
    }
    return output === null ? 0 : parseInt(output)
}

2 个答案:

答案 0 :(得分:2)

  

我不确定他们为什么期望以下输出-2147483648而不是-91283472332

因为:

  

假设我们正在处理的环境只能存储32位有符号整数范围内的整数:[− 2 31 ,2 31 − 1]。如果数值超出可表示值的范围,则返回INT_MAX(2 31 -1)或INT_MIN(-2 31 )。

因此,如果提取的数字大于2 ** 31 - 1,则返回的数字应改为2 ** 31 - 1

类似地,如果提取的数字小于-(2 ** 31),则返回-(2 ** 31)

使用正则表达式可能会更容易:

const myAtoi = (str) => {
  const match = str.match(/^ *([+-]?\d+)/);
  if (!match) return;
  const num = Number(match[1]);
  return Math.max(
    Math.min(2 ** 31 - 1, num),
    -(2 ** 31)
  );
};

console.log(
  myAtoi('    123'),
  myAtoi('-456'),
  myAtoi('-9999999999999'),
  myAtoi('9999999999999')
);

答案 1 :(得分:0)

看看这个解决方案。当我们处理整数时,它们仅保留32位。 2 ^ 31

class Solution {
    public int myAtoi(String str) {

        int flag=0, sign = 0;
        int n = str.length();
        StringBuilder st = new StringBuilder();
        int i =0;

        //clear white spaces
        while(i<n && str.charAt(i) == ' '){
            ++i;
        }

        //overflow of string
        if (i>=n){
            return 0;
        }

        //checking sign and not allowing more than one sign, will return 0 if there is ++,+-,--
        while(i<n && (str.charAt(i) == '+' || str.charAt(i) == '-')){
            if (sign >= 1){
                return 0;
            }
            else{
           st.append((str.charAt(i++) == '+') ? '+': '-');
            sign++;
            }

        }

        //checking if character is digit
        while(i<n && Character.isDigit(str.charAt(i))){
            st.append(str.charAt(i++));
            flag = 1;
        }

        //return 0 if no digits
        if(flag == 0)
            return 0;

        //to check if the number is within the int range
        try{
            return Integer.parseInt(st.toString());

        }
        catch(NumberFormatException e){
            return (st.charAt(0) == '-') ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        }



    }
}