CodeBox CodeBox

JavaScript Reverse Integer

Typescript / JS
けい

1. 🧐 Expected Output

reverseInt(15) === 51;
reverseInt(981) === 189;
reverseInt(500) === 5;
reverseInt(-15) === -51;
reverseInt(-90) === -9;

2. 🤔 My Solution

function reverseInt(n) {
  const arr = n.toString().split('').reverse().filter(el => el !== '-')
  const numberArr = []

  for (let index = 0; index < arr.length; index++) {
    if (arr.length >= 2 && arr[0] === '0'){
      arr.shift()
    }
    numberArr.push(arr[index])
  }

  const _numberArr = parseInt(numberArr.join(''))

  if (n < 0) return -1 * parseInt(_numberArr)
  return parseInt(_numberArr)
}

3. 🎊 Best Solution

3-1. First Solution

  • parseInt() method can handle the string like "001"
  • parseInt() method change "001-" into 1
function reverseInt(n) {
  const reversed = n.toString().split('').reverse().join('')

  if (n < 0) return parseInt(reversed) * -1
  return parseInt(reversed)
}


3-2. Second Solution

  • Call Math.sign()
  • Math.sign(number) returns -1 or 0 or -0 or 1
  • if number is negative, Math.sign returns -1
  • if number is positive, Math.sign returns 1
  • if number is negative zero, Math.sign returns -0
  • if number is zero, Math.sign returns 0
function reverseInt(n) {
  const reversed = n.toString().split('').reverse().join('')
  return parseInt(reversed) * Math.sign(n)
}

ABOUT ME

けい
ベンチャーのフロントエンジニア。 主にVueとTypescriptを使っています。ライターのための文字数カウントアプリ:https://easy-count.vercel.app/