To prove safety offer- string into an integer

Converting a string to an integer

Converting a string to an integer, the request can not use the library function converts the integer string. Value of 0 or a character string is not a valid value of 0 returns
Input Description:
enter a character string including alphanumeric symbols, can be empty
output Description:
If the expression is valid number value is returned, otherwise 0

Problem-solving ideas

Analyzing means of solving the problem is represented by the string is not an integer, a string can sign the front, behind only numbers, letters or other symbols can not have. Also consider the overflow problem, that number must be between [-2 ^ 31,2 ^ 31-1].

  • The first step: first judgment, not a number, then only '+' or'- 'and can not be only one
  • Step two: from the beginning to traverse the string, the first is to skip the first symbol, not a number to return immediately, while the integer calculation
  • The third step: Return results

Calculating an absolute value of an integer, it must be a positive number if <= 2 ^ 31-1, if the negative must be <= 31 ^ 2;
with a variable limit record this boundary, the default is 2 ^ 31-1, when the negative to update

function StrToInt(str)
{
    if(str.length == 0) return 0
    let res = 0,flag = 1
    let limit = 2147483647  //2^31-1
    let i=0
    //若第一位不是数字,则必须是‘+’‘—’且不能只有一位
    if(!(str[0]>'0'&&str[0]<'9')){
        if(str[0]==='-'){
            limit = 2147483648
            flag = -1
        }else if(str[0]!='+'){  //不是'-'就只能是'+'
            return 0
        }
        if(str.length == 1) return 0
        i++  //跳过符号位
    }
    
    let limitmin = limit/10  //针对res*10可能越界建立的变量
    for(;i<str.length;i++){
        if(!(str[i]>'0'&&str[i]<'9')){
            return 0
        }
        //边界处理分为两步,因为这两步都可能越界
        if(res>limitmin) return 0
        res = res*10
        if(res+(str[i]-'0')>limit) return 0  //str[i]-'0'把字符串转化为数字的方法
        res = res+(str[i]-'0')
    }
    return res*flag
}
Published 21 original articles · won praise 0 · Views 165

Guess you like

Origin blog.csdn.net/adrenalineiszzz/article/details/105001821