Problem · Math

Reverse an Integer

Learn this problem
EasyMicrosoft logoMicrosoftINTERNOA
See Microsoft hiring insights

Problem statement

Reverse the decimal digits of an integer, positive or negative, without converting the integer to a string or using string manipulation.

Complete reverse(int x). Preserve the sign, discard leading zeros in the reversed digits, and return 0 if the reversed value falls outside the signed 32 bit integer range.

🍊 Source note (Jul 17, 2026): The source did not specify what should happen when the reversed value overflows a signed 32 bit integer. This version returns 0 in that case. The judged core task matches the visible source at about 98%.

Function

reverse(x: int) → int

Examples

Example 1

x = 123return = 321

The reversed integer is 321. Since the reversed integer is within the signed 32-bit integer range, it is the return value.

Example 2

x = 120return = 21

The reversed integer is 21. Notice that the leading zero in the input integer is not present in the reversed integer.

Example 3

x = -120return = -21

The reversed integer is -21. The negative sign is preserved during the reversal.

Constraints

  • -2^31 <= x <= 2^31 - 1

More Microsoft problems

drafts saved locally
public int reverse(int x) {
  // write your code here
}
x123
expected321
checking account