7. Reverse Integer

 Reverse Integer

Reverse Integer

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

 

Example 1:

Input: x = 123
Output: 321


Example 2:

Input: x = -123
Output: -321


Example 3:

Input: x = 120
Output: 21

 
Constraints:

  • -231 <= x <= 231 - 1

Idea:

For this solution, we take the provided number, get its absolute value (that is to say, we remove any negative symbol), convert it to a string, convert that string to an array, reverse the array, join the array back into a string, parse it into a number, and re-negate it if necessary.

-1234             // Number in
1234 // Absolute value
"1234" // String value
["1","2","3","4"] // Array value
["4","3","2","1"] // Reverse array value
"4321" // Joined array
4321 // Parsed number
-4321 // Negated number
Let`s Code IT!
var reverse = function (num) {
    // Conver the number to a string, split it to an array, reverse it, and then re-join it
    const reversedNumber = parseInt(
        Math.abs(num).toString().split('').reverse().join('')
    );

    // Check for an invalid output
    if (reversedNumber > 2147483647) {
        return 0;
    }

    // Return the reversed number (negating it if the original number was negative)
    return num < 0 ? -Math.abs(reversedNumber) : reversedNumber;
};
OR
const reverse = n => (n < 0 ? -1 : 1) * +("" + Math.abs(n)).split``.reverse().join``;

Conclusion

That’s all folks! In this post, we solved LeetCode problem #7. Reverse Integer

I hope you have enjoyed this post. Feel free to share your thoughts on this.

You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.


In this blog, I have tried to solve leetcode questions & present the most important points to consider when improving Data structure and logic,  feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!

Comments

Popular Post