preface

Two days ago, I was busy dealing with other things, so I simply looked at the algorithm problem, and did not send it to share with you, and now IT is going to brush the simple problem of force buckle first, so today to the majority of fans is force buckle 7 problem solution ideas and code, I hope you support…

Topic describes

You are given a 32-bit signed integer x that returns the result of reversing the numeric portion of x.

If the inverted integer exceeds the range of 32-bit signed integers [-22147483648, 2147483647], 0 is returned.

Example 1:

Enter x = 123

Output: 321

Example 2:

Enter x = -123

Output: – 321

Example 3:

Enter: x = 120

Output: 21

Answer: Convert X from Number object to String object, use String method split to split String into Array, then use reverse method of Array object to reverse, and then use join method of Array object to convert Array into String. Finally, change String back to Number. And then I’m going to do the bit operation on the minus sign and I’m going to take the minus plus 1 and return 0 if I go out of range

Coding:

/ * * *@param {number} x
 * @return {number}* /
var reverse = function(x) {
    var str = x.toString()
    let arr = str.split(' ') / / array
    // Check if there is a negative sign
    if(arr[0]! = =The '-') {let num = Number(arr.reverse().join(' '))
        if(num <= 2147483647 && num >= -22147483648) {return num
        } else {
          return 0}}else if(arr[0= = =The '-') {delete arr[0]
        let num = Number(arr.reverse().join(' '))
        if(num <= 2147483647 && num >= -22147483648) {return ~num+1
        } else {
          return 0}}};// Time complexity O(n)
// Space complexity O(n)
Copy the code

Code simplification:

var reverse = function (x) {
    let y = parseInt(x.toString().split("").reverse().join(""));
    if (x < 0)
        y = - y;
    return y > 2147483647 || y < -2147483648 ? 0 : y;
};
Copy the code

conclusion

Brush the sixth day, choose buckle 7, learn to reverse integer, refueling wow ~

❤️ thank you

If you think this content is quite helpful to you: click the like to support it, so that more people can see this content (collection does not like, are playing hoagie – -) pay attention to the public account to NPY front-end secrets, we learn together and progress together. If you feel good, you can also read other articles (thanks to friends for their encouragement and support 🌹🌹🌹)

Start the LeetCode journey

Double pointer to LeetCode

Leet27. Remove elements

Front-end engineers must learn the classic sorting algorithm

LeetCode20. Brackets match