Write a reverse integer function using string and array methods

Share this video with your friends

Social Share Links

Send Tweet

In this lesson you will learn how to write an interview coding task which challenges you with reversing the integer and keeping the original sign intact. You will use different methods like toString, reverse, split and join to achieve the needed functionality using functional programming approach.

Dimitri Ivashchuk: [0:00] At the interview you are asked to reverse an integer with keeping the sign of the initial integer. Let's write the function for that. Const reverseInt. We want to pass the integer to it, and then we want to return something.

[0:21] First of all, we want to cast the integer to string so we can use method toString. Then we want to split the string and we want to split each individual character of the string. Then we want to reverse the array of characters that we got from string split, and then we want to join them back.

[0:44] Let's console log what we have now. Let's call it reversedString. Now let's call the reverseInt with int. You see that we have reverted the string indeed, but the minus is now at the last place of the string. We want to cast this string to an integer, for that we can use parseInt.

[1:18] PasrseInt reversedString. This gives us the integer for that string. What we are actually missing is the initial sign of the original integer that we passed. Let's fix that. To do that, we need to multiply the integer that we got from parsetInt with the Math.sign of the initial integer, which would be the minus sign.

[1:47] This effectively gives us the result that we wanted. To make the function work, let's just return what we got here. Now we can console log the reverseInt with int...