Question
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
Constraints:
- -231 <= x <= 231 - 1
Let's Go!
Solve by using PREP.
- P - One parameter. A number x
- R - Return the reverse of the number
- E - Examples provided by question. (See Above)
- P - See Below
var reverse = function(x) {
const reversed = x
.toString()
.split('')
.reverse()
.join('');
return parseInt(reversed) * Math.sign(x);
};
Translate into code...
var reverse = function(x) {
// Convert x from number to string
// Split string into array of elements
// Apply reverse method
// Join String
const reversed = x
.toString()
.split('')
.reverse()
.join('');
// Convert string to number & multiple by the sign of x
// Return the above
return parseInt(reversed) * Math.sign(x);
};
Conclusion
& Remember... Happy coding, friends! =)
Top comments (0)