Math Number tricks

91. Reverse Integer

Medium

You are given a signed 32-bit integer x. Return the number you get by writing the digits of x in reverse order. The sign stays as it is, and zeros that end up at the front are dropped, so 1200 becomes 21 and −35 becomes −53.

A signed 32-bit integer holds the values from −231 to 231 − 1, that is from −2,147,483,648 to 2,147,483,647. If the reversed number is outside that range, return 0.

Interviewers ask for this problem to be solved with 32-bit integers only, as if no wider type existed. So no value in your code should go outside that range, even for a moment.

Example 1

Input: x = 1999999999

Output: 0

Explanation: The digits reversed give 9,999,999,991. That is larger than 2,147,483,647, so the answer is 0.

Example 2

Input: x = -473

Output: -374

Explanation: The sign stays, and the digits 473 reversed are 374.

Example 3

Input: x = 8150

Output: 518

Explanation: The digits reversed are 0518. The zero at the front is dropped, so the answer is 518.

Check your understanding

Work out the answer for this input before you write any code.

x = 1563847412

Constraints

  • -231 ≤ x ≤ 231 − 1

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.