Coding problem · Easy · Basics

Reverse an Integer

Easy Algorithms & data structures

Return n with its digits reversed, keeping the sign. Leading zeros disappear: 120 becomes 21. |n| < 10^9.

Example 1

Input: n = 123
Output: 321

Example 2

Input: n = -456
Output: -654

Example 3

Input: n = 120
Output: 21

Hints

Hint 1

Work with the absolute value and remember the sign.

Hint 2

Build the result digit by digit: result = result × 10 + n % 10.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(digits) · Space O(1)

Peel digits off the end with % 10 and push them onto the result with × 10 +. Apply the original sign at the end.

Reference solution

function reverseInteger(n) {
  let x = Math.abs(n), result = 0;
  while (x > 0) { result = result * 10 + (x % 10); x = Math.floor(x / 10); }
  return n < 0 ? -result : result;
}

Was this page helpful?