Problems/Math and Geometry/Reverse 32-Bit Integer
Math and Geometry
medium

Reverse 32-Bit Integer

Given a 32-bit signed integer, cyclically right-shift its digits by a specified amount. If the resulting integer falls outside the 32-bit signed integer range, return 0.

MathBit ManipulationInteger ManipulationCyclic ShiftOverflowModulo

Problem Statement

You are given a 32-bit signed integer num and a non-negative integer shift. Your task is to cyclically right-shift the digits of num by shift positions. If the shifted integer overflows or underflows the range of a 32-bit signed integer [-2^31, 2^31 - 1], return 0. Assume that the environment only allows you to store integers within the 32-bit signed integer range.

Example 1
Input: {num: 12345, shift: 2}
Output: 45123
Cyclically right-shifting 12345 by 2 positions results in 45123.
Example 2
Input: {num: -123, shift: 1}
Output: -312
Cyclically right-shifting -123 by 1 position results in -312.
Constraints
  • --2^31 <= num <= 2^31 - 1
  • -0 <= shift <= 10^9
  • -The shift operation must be cyclic, meaning digits shifted off the right end reappear on the left end.
  • -The sign of the number must be preserved after the shift.

Brute Force Approach

A brute-force approach would involve converting the integer to a string, performing the cyclic shift on the string, and then converting the string back to an integer. This is like manually rearranging the letters in a word to achieve the desired shift. Finally, check if the resulting integer is within the valid 32-bit range, and return 0 if it's not.

TimeO(n)
SpaceO(n)

Ready to practice?

Work through this problem with AI coaching and get real-time feedback

Practice This Problem