480.Reverse the Digits of a Number
Easy
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).
Example 1:
Input: n = 123
Output: 321
Example 2:
Input: n = 120
Output: 21
Example 3:
Input: n = 0
Output: 0
+ 4 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ n ≤ 1000000000
n =
123