Reverse the digits of an integer
Reverse the decimal digits of an integer while preserving its sign and dropping leading zeroes from the reversed result.
Course progress
Problem 56 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
number = -1204
Expected output
-4021
What is happening?
Reverse the absolute-value digits 1,2,0,4 to 4,0,2,1, then restore the negative sign. The zero remains inside the number rather than becoming a leading zero.
Solution strategy
Build the right mental model
Work with the absolute value, repeatedly append the last digit to a result, then apply the original sign.
Core concepts
modulo · loops
Complexity
Time O(d), space O(1), where d is the number of digits.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for reverse-integer-digits
using System;
class Program
{
static long ReverseDigits(int number)
{
long remaining = Math.Abs((long)number);
long reversed = 0;
while (remaining > 0)
{
reversed = reversed * 10 + remaining % 10;
remaining /= 10;
}
return number < 0 ? -reversed : reversed;
}
static void Main()
{
Console.WriteLine(ReverseDigits(-1204));
}
}Knowledge check
Questions students often ask
What is the main idea behind reverse the digits of an integer?
Work with the absolute value, repeatedly append the last digit to a result, then apply the original sign.
What is the time and space complexity of this solution?
Time O(d), space O(1), where d is the number of digits.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.