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

Blog    

Recommend

MySQL 5.7.17 Compressed Version Installation Notes

This article shares the installation steps of MyS...

Vue implements the countdown component for second kills

This article shares the specific code of Vue to i...

Implementation of Docker CPU Limit

1. --cpu=<value> 1) Specify how much availa...

Implementation of sharing data between Docker Volume containers

What is volume? Volume means capacity in English,...

js memory leak scenarios, how to monitor and analyze them in detail

Table of contents Preface What situations can cau...

How much do you know about JavaScript inheritance?

Table of contents Preface The relationship betwee...

Solve the problem of MySql client exiting in seconds (my.ini not found)

Problem description (environment: windows7, MySql...

Solve the abnormal error when building vue environment with webpack

Table of contents First, configure package.json T...

Detailed explanation of the flexible use of CSS grid system in projects

Preface CSS grids are usually bundled in various ...

Using CSS3's 3D effects to create a cube

Learning to use CSS3's 3D effects to create a...

Share MySql8.0.19 installation pit record

The previous article introduced the installation ...

Detailed explanation of MYSQL log and backup and restore issues

This article shares MYSQL logs and backup and res...

Summary of bootstrap learning experience-css style design sharing

Due to the needs of the project, I plan to study ...