As I mentioned before i want to reverse a number with minus sign
expected output
141-
my output is
-141
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function (x) {
var reversedNum = parseFloat(x.toString().split('').reverse().join('')) * Math.sign(x);
return reversedNum;
};
console.log(isPalindrome(-141));
const isPalindrome = (x) => {
const str = new String(x);
return Array.from(str).reverse().join('');
}
Taking it step by step:
x = -141
-141.toString() = "-141"
"-141".split('') = ["-","1","4","1"]
["-","1","4","1"].reverse() = ["1","4","1","-"]
["1","4","1","-"].join('') = "141-"
parseFloat("141-") = 141
Math.sign(-141) = -1
141 * -1 = -141
If you are attempting to output a number type that is serialized as 141-, that is impossible. If you want a string output, there is no reason to parse as a float as the trailing - is ignored. So simply remove the parseFloat() and * Math.sign(x).
However, your JSdoc dictate that the function should return a boolean, and the function is named isPalindrome, indicating it should return if the input is the same reversed. In which case I would expect something like:
var isPalindrome = function (x) {
return x.toString() === [...x.toString()].reverse().join('');
};
const isPalindrome = number => number.toString().split("").reverse().join("")
number = -142
toString() method converts the number to string. // "-141"
split("") method converts the string to array. // ["-", "1", "4", "1"]
reverse() method reverse the array. // ["1", "4", "1", "-"]
join("") method returns the array as a string. // "141-"