'How to reverse a number/string in NodeJS?
I have used this code to reverse a number but it is not working.
var buffer = new Buffer("<inputNumber>", "ucs2");
Array.prototype.reverse.call(new Unit16Array(buffer));
return buffer.toString("ucs2");
Where was I wrong? Is this approach right? Any other way of reversing a number/string without using buffer?
Solution 1:[1]
There are different ways to convert number to string :
String literal -> str = "" + num + "";
String constructor -> str = String(num);
toString -> str = num.toString();
String Literal simple -> str = "" + num;
The split() method is used to split a String object into an array of strings by separating the string into substrings.
Code : console.log('1000'.split(""));
Output : ["1", "0", "0", "0"]
The reverse() method is used to reverse an array in place. The first array element becomes the last and the last becomes the first.
Code : console.log(["1", "0", "0", "0"].reverse());
Output : ["0", "0", "0", "1"]
The join() method is used to join all elements of an array into a string.
Code : console.log(["1", "0", "0", "0"].reverse().join(""));
Output : "0001"
Solution 2:[2]
To reverse a number first you have to convert it into string. Convert that string into array. Reverse the array and join it to make a string then parse that string to number
var num = 1543;
var reverseNum = parseInt(a.toString().split("").reverse().join(""));
//Output : 3451
I hope this will help you.
Solution 3:[3]
Though the question is for numbers, it does also ask about strings, and was Google's first answer.
function reverse(value) {
return Array.from(
String(value || '')
).reverse().join('')
}
Be careful of using string.split('') to split the given string into its characters. The String#split method doesn’t handle UTF-16 characters like emojis. The list of characters would then lose the emojis as individual characters. That’s the reason we recommend using Array.from() to create an array of characters from a given string.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Neha Tawar |
Solution 2 | Saurabh Lende |
Solution 3 | Regular Jo |