How to flip a number in JS?

  • 0
    My solution, but doesn't work for the last case. Problems appear if zeros occur in the middle of a number. What can you do about it?

    const reverseNumber = num => {
      const str = (Math.abs(num)).toString()
      let res = ''
      const isNegative = num < 0
      
      for (let i = 0; i < str.length; i++){
        const char = str[i]
        if (char !== '0') res = char + res
        else if (char === '0' && str[i + 1] && str[i + 1] !== '0') res = char + res
      }
    
      return Number(isNegative ? res * -1 : res)
    }
    
    console.log(reverseNumber(-456))  //  -654
    console.log(reverseNumber(1000))  //  1
    console.log(reverseNumber(901))  //  109
    console.log(reverseNumber(50078))  //  87005
    JavaScript Anonymous, Aug 21, 2020

  • 5 Answers
  • 0
    const reverseNumber = num =>
    num >= 0
    ? +`${num}`.split('').reverse().join('')
    : -(`${-num}`.split('').reverse().join(''))
    Josephine Petersen

  • 0
    const reverseNumber = num => Math.sign(num) * [...`${Math.abs(num)}`].reverse().join('');
    Anonymous

  • 0
    And what is the number 0001? Return it as a string.
    Anonymous

  • 0
    I'm adding pseudocode.



    Convert to string

    Check 1 character for minus keep the flag if negative and truncate the string by 1 character



    Apply the reverse method

    Call parseInt

    If the checkbox is minus then return with minus if not then as it is
    Silas Lowery

  • 0
    reverseNumber=n=>(n<0?-1:1)*parseInt(n.toString().split('').reverse().join(''));
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!