Reverse the Digits of a Number

Solve this Problem
Easy10 min
Topics
Companies
Given a non-negative integer n, return the number formed by reversing its digits. Any leading zero that would result (as with 120 → 021) is simply dropped, same as it would be for any ordinary number. The digit-by-digit loopDigit-by-Digit LoopPeeling digits off n with % 10 and / 10 while shifting a running "reversed" value left (× 10) to make room for each new digit. builds the answer purely with arithmetic, the same way in every language. The string reversal trickString ReversalConverting the number to text, reversing the characters, then parsing the result back into a number. treats it as a text problem instead — shorter to write, but dependent on each language's string tools (and, as the leading-zero case shows, on the parser to clean up the result).

Test Case 1:

Input:n = 123
Output:321
Explanation:Reading 123's digits backward gives 321.

Test Case 2:

Input:n = 120
Output:21
Explanation:The leading zero that would result (021) is simply dropped, same as any number.

Test Case 3:

Input:n = 0
Output:0
Explanation:Zero reversed is still zero.

Constraints

  • ◆0 ≤ n ≤ 1000000000

Try the Dry Run

Approach & Solutions

Loop — Build the Reversed Number Digit by DigitOptimal

Pull off n's last digit with % 10, then shift the running "reversed" value one place left (multiply by 10) and drop that digit in. Repeat until n is fully consumed — the first digit pulled off ends up in the last position of the result, and the last digit pulled off ends up first.

TimeO(d) — d is the number of digits
SpaceO(1)
1class Solution { 2 public int reverseNumber(int n) { 3 int reversed = 0; 4 while (n != 0) { 5 int digit = n % 10; 6 reversed = reversed * 10 + digit; 7 n = n / 10; 8 } 9 return reversed; 10 } 11}
String Reversal TrickGood

Convert n to a string, reverse the characters, and parse the result back into a number. A shortcut that leans on built-in string operations instead of digit arithmetic — simple to read, though it needs a reverse-capable string type (or a manual in-place swap, as in C) rather than working with the number directly.

TimeO(d)
SpaceO(d)
1class Solution { 2 public int reverseNumber(int n) { 3 String s = String.valueOf(n); 4 String reversedStr = new StringBuilder(s).reverse().toString(); 5 return Integer.parseInt(reversedStr); 6 } 7}

Related Problems