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;
}
function reverseInteger(n: number): number {
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;
}
def reverse_integer(n: int) -> int:
result = int(str(abs(n))[::-1])
return -result if n < 0 else result
<?php
function reverseInteger(int $n): int
{
$result = (int) strrev((string) abs($n));
return $n < 0 ? -$result : $result;
}
class Solution {
public int reverseInteger(int n) {
int x = Math.abs(n), result = 0;
while (x > 0) { result = result * 10 + x % 10; x /= 10; }
return n < 0 ? -result : result;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy