preface

Our community will continue to add Yi Gu (Netflix growth hacker, author of “The Way to Interview for iOS”, ACE professional fitness coach. Swift algorithm solution sorted into text version to facilitate everyone to learn and read.

We have updated 3 issues of LeetCode algorithm so far, and we will keep the update time and progress (Monday, Wednesday and Friday at 9:00 a.m.). There is not much content in each issue, so we hope you can read it on your way to work, and there will be great improvement in long-term accumulation.

Short step, no thousands of miles; No small streams, no rivers and seas, Swift community with you forward. If you have suggestions and comments welcome to leave a message at the end of the article, we will try our best to meet your needs.

Difficulty level: Medium

1. Describe

Given a signed 32-bit integer x, return the numeric inversion of x. If reversing x results in a value outside the range of signed 32-bit integers -$2^31$<= x <= $2^31$-1, then 0 is returned.

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

Example 2.

Example 1

Input: x = 123 Output: 321Copy the code

Example 2

Input: x = -123 Output: -321Copy the code

Example 3

Input: x = 120 Output: 21Copy the code

Example 4

Input: x = 0 Output: 0Copy the code

Constraints:

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

3. The answer

class ReverseInteger {
    func reverse(_ x: Int) -> Int {
        var res = 0
        var x = x
        while x ! = 0 {
            if res > Int(Int32.max) / 10 || res < Int(Int32.min) / 10 {
                return 0
            }
            res = res * 10 + x % 10
            x = x / 10
        }
        return res
    }
}
Copy the code
  • Main idea: Iterate backwards over the digits of numbers using % 10 and update the results accordingly using * 10.
  • Note: Handle integer overflow when appropriate.
  • Time complexity: O(n)
  • Space complexity: O(1)

Leetcode-swift is a repository for solving problems of this algorithm

Click to go to LeetCode practice

About us

We are jointly maintained by Swift enthusiasts. We will share technical content based on Swift combat, SwiftUI and Swift foundation, as well as collect excellent learning materials.

The follow-up will also translate a large number of information to our public account, interested friends, can join us