A brief discussion on the magic of parseInt() in JavaScript

A brief discussion on the magic of parseInt() in JavaScript

cause

The reason for writing this blog is that I was doing the daily question of Leetcode today. It is a question about converting a string to an integer (atoi). If you are interested, you can click on the title to see the detailed description. After I debugged it many times and finally submitted it successfully, I went to the comment section to see the experts' solutions. After reading it, I couldn't help but sigh that parseInt() in JavaScript is so excellent. This tells me a truth: the APIs that we think we are very familiar with may not be truly mastered by us. ”

My answer

/**
 * @param {string} str
 * @return {number}
 */
var myAtoi = function(str) {
    str = str.trim();
    //Intercept the first character of the string var firstChar = str.charAt(),res = '',regSymbol = /^[\-\+]{1}/,regNumber = /^[0-9]{1}/;

    if(!regSymbol.test(firstChar) && !regNumber.test(firstChar)){
        return 0;
    }

    //The first character is + or -
    if(regSymbol.test(firstChar)){
        var sliceStr = str.slice(1,str.length);
        for(var i=0;i<sliceStr.length;i++){
            if (regNumber.test(sliceStr.charAt(i))) {
                res += sliceStr.charAt(i);
            }else{
                break;
            }
        }
        
        (res.length) ? res = parseInt(firstChar + res) : res = 0;

        if(firstChar == '-' && res < Math.pow(-2,31)){
            res = Math.pow(-2,31);
        }

        if(firstChar == '+' && res > Math.pow(2,31) - 1){
            res = Math.pow(2,31) - 1;
        }

        return res;
    }

    //The first character is a number if (regNumber.test(firstChar)) {
        var sliceStr = str;
        for(var i=0;i<sliceStr.length;i++){
            if (regNumber.test(sliceStr.charAt(i))) {
                res += sliceStr.charAt(i);
            }else{
                break;
            }
        }

        if (parseInt(res) > Math.pow(2,31) - 1) {
            res = Math.pow(2,31) - 1;
        }

        return res;
    }
};

The answer from the boss

/**
 * @param {string} str
 * @return {number}
 */
var myAtoi = function(str) {
    const number = parseInt(str, 10);

    if(isNaN(number)) {
        return 0;
    } else if (number < Math.pow(-2, 31) || number > Math.pow(2, 31) - 1) {
        return number < Math.pow(-2, 31) ? Math.pow(-2, 31) : Math.pow(2, 31) - 1;
    } else {
        return number;
    }
};

By comparison, we know that parseInt() in JavaScript has performed a series of operations such as intercepting empty strings, judging the first letter, and returning number type results. It just happens to be a perfect match for today's daily question. It's so cool to use parseInt() to solve this problem.

This is the end of this article about the wonderful uses of parseInt() in JavaScript. For more relevant JavaScript parseInt() content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Exploration and correction of the weird behavior of parseInt() in js
  • Detailed explanation of JS conversion functions Number(), parseInt(), parseFloat()
  • In-depth understanding of Number(), parseInt(), and parseFloat() in JS
  • Detailed explanation of the difference between Number(), parseInt() and parseFloat() in js
  • Analysis of parseInt() and map() usage in JS
  • Definition and usage analysis of parseInt() function in javascript
  • Javascript function parseInt() has a bug when converting
  • Introduction to the use of the parseInt() method of the global object in javascript
  • JavaScript parseInt() function base conversion attention details

<<:  How to implement Linux deepin to delete redundant kernels

>>:  How to find out uncommitted transaction information in MySQL

Recommend

A brief discussion on MySql views, triggers and stored procedures

view What is a view? What is the role of a view? ...

Security considerations for Windows server management

Web Server 1. The web server turns off unnecessar...

Detailed explanation of how to use the calendar plugin implemented in Vue.js

The function to be implemented today is the follo...

Docker installs mysql and solves the Chinese garbled problem

Table of contents 1. Pull the mysql image 2. Chec...

How to implement the strategy pattern in Javascript

Table of contents Overview Code Implementation Su...

Complete steps to configure a static IP address for a Linux virtual machine

Preface In many cases, we will use virtual machin...

Solve the black screen problem after VMware installs Linux system and starts

1. Installation environment 1. HUAWEI mate x cpu ...

How to make vue long list load quickly

Table of contents background Main content 1. Comp...

Tutorial on installing the unpacked version of mysql5.7 on CentOS 7

1. Unzip the mysql compressed package to the /usr...

HTML Form Tag Tutorial (4):

Suppose now you want to add an item like this to ...

Summary of pitfalls of using nginx as a reverse proxy for grpc

background As we all know, nginx is a high-perfor...

Hbase Getting Started

1. HBase Overview 1.1 What is HBase HBase is a No...