Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize integer inversion by LeetCode

Shulou Source: shulou.com Published: 2022-06-01 13:08:19 10月19日 Update

This article mainly shows you "LeetCode how to achieve integer inversion", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "LeetCode how to achieve integer inversion" this article.

Topic description (@ LeetCode)

Given a 32-bit signed integer, you need to reverse the number on each of the integer.

Example 1:

Input: 123 output: 321

Example 2:

Input:-123 output:-321

Example 3:

Input: 120 output: 21

Returns 0 if the inverted integer overflows the 32-bit int range.

Second, the way to solve the problem

Using modular and rounding operations to separate each position, and then accumulate:

123% 10 = 3: take the lowest bit 123 / 10 = 12: remove the lowest bit to check for overflow INT_MAX = 2 ^ 31-1 = 2147483647INT_MIN =-2 ^ 31 =-2147483648 if rec > 2147483647 / 10 = 214748364, then the following rec * 10 must overflow, for example, 2147483650 if rec = 2147483647 / 10 = 214748364 and pop > 7, the same mathematical method class Solution {if the subsequent rec just does not overflow less than 0.

Public:

Int reverse (int x) {

Int rec = 0

Int pop = 0

While (x) {

/ / 1. Take the last place 123% 10 = 3 at a time

Pop = x% 10

/ / 2. Get rid of the last 123 / 10 = 12

X = x / 10

/ / 3. If rec > 2147483647 / 10 = 214748364, subsequent rec * 10 must overflow, such as 214748365 * 10

/ / 4. If rec = 2147483647 / 10 = 214748364 and pop > 7, the subsequent rec just won't overflow.

If ((rec > INT_MAX / 10) | | (rec = = INT_MAX / 10) & & (pop > 7)) return 0

/ / 5. Negative numbers are the same.

If ((rec < INT_MIN / 10) | | (rec = = INT_MIN / 10) & & (pop <-8)) return 0

/ / 6. Cumulative 123 = 12 * 10 + 3

Rec = rec * 10 + pop

}

Return rec

}

}

Complexity Analysis time complexity: O (log (n)) Space complexity: O (1)

The above is all the contents of the article "how to achieve integer inversion in LeetCode". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Integers complexity content complexity examples articles input output minimum numbers learning help location ideas situations math methods time easy to understand more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft macOS OPPO Reno vpn Redmi