NOTE

Reverse Integer

Reverse the decimal digits of a 32-bit signed integer and handle overflow.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Problem Description

Given a 32-bit signed integer x, return the result of reversing the digits of x.

If the reversed integer exceeds the 32-bit signed integer range [−2^31, 2^31 − 1], return 0.

Assume the environment does not allow storing 64-bit integers (signed or unsigned).

2. Approach

  1. Approach 1
    1. Take the remainder modulo 10, then multiply by 10

3. Implementation

func reverse(x int) int {
    var res int32 = 0// Must use int32
    for x != 0 {
        oldRes := res// Whether it overflows
        res = res * 10 + int32(x % 10)
        if res / 10 != oldRes {// Whether it overflows
            return 0
        }
        x /= 10
    }
    return int(res)
}

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub