Hi all, I'll make this quick and go straight to the meat and paneer :) of things.
Reversing a string or reversing a number is one of the common questions asked at programming interviews. Let’s take a look at how this is done.
Limitations/Rules:
negative numbers should remain negative
any leading zeroes must be removed
function that can accept floats or integers
the function will return integers a integers
//enclose your code in parsefloat first
const reversedNum = num => { parseFloat(num.toString()
.split('')
.reverse()
.join(''))*Math.sign(num) //make sure you multiply by this to correct the negative sign
}
reverseNum(1234) // 4321
Ok, so now we have mentioned the limitations, let's break down the following arrow function solution into step.Arrow functions have an implicit return value — if they can be written in one line, without the need for the{} braces.
- Notice, first we must convert the number into a string in order to use the split array method. num.toString() converts the given number into a String so we can use the split function on it next.
- the split function - takes a a string and turns it into a array of characters, we need to do this in order to use the next array reverse function.
- Reverse the array - num.reverse() reverses the order of the items in the array
- join() function - num.join() function - combines the reversed characters into a string.
- Parse the input value into a floating point number. parseFloat(num) converts num into a float from a String. Notice the example below, it removes the 0s and the - and gives you only the float point numbers.
num = '0012345-'
parseFloat(num)
//num - 12345
- Multiply it by the sign of the original number in order to maintain the negative value. num* Math.sign(num)
original value of num = -5432100
//num = 12345
num * Math.sign(-5432100)
//num = -12345
and there you have it!
Top comments (0)