The sword refers to offer(49) to convert strings to integers.

Topic description

Converting a string to an integer requires library functions that cannot use strings to convert integers. Returns 0 if the value is 0 or the string is not a valid value

Enter description:

Enter a string, including alphanumeric characters, can be empty

Output description:

Returns the number if it is a valid numeric representation, otherwise returns 0

 

topic analysis

This kind of question is often tested, that is, it is required not to use library functions, but to write it yourself.

This kind of question requires us to have a relatively deep understanding of the implementation principle of library functions. Some questions will be difficult, and we should examine the degree of mastery of the basics.

But this question is simpler.

 

code

function StrToInt(str)
{
    let res=0,flag=1;
    let n=str.length;
    if(!n) return 0;
    if(str[0]=="-"){
        flag=-1;
    }
    for(let i=(str[0]=="+"||str[0]=="-")?1:0;i<n;i++){
        if(!(str[i]>="0"&&str[i]<="9")) return 0;
        res=(res<<1)+(res<<3)+(str[i]-"0");
    }
    return res*flag;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324637754&siteId=291194637