Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 7 · Math

Reverse Integer

LeetCode 7 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

num = num·10 + x % 10, then range-check.

நடுத்தரம்Math
LeetCode இல் திற ↗

நான் Reverse Integer (LeetCode 7) ஐ இப்படித் தீர்த்தேன் — Math பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Peel digits off the end with % 10 and push them onto a new number with ×10. Handle the sign separately, then reject results outside the signed 32-bit range.

Approach

  1. 1

    Remember the sign and work with |x|.

  2. 2

    Repeatedly take the last digit and append it to num.

  3. 3

    Restore the sign; if outside 32-bit range, return 0.

நான் எப்படித் தீர்த்தேன்

Digit poppingPythonO(log x) time · O(1) space
class Solution:
    def reverse(self, x: int) -> int:
        #num=0
        #123%10 -> remainder 3
        #num = num*10+remainder ->3
        #num = 3*10+2 - 32
        #num = 32*10+1
        sign=1
        if x<0:
            sign=-1
            x = (-1)*x
        num = 0
        while x>0:
            remainder = x%10
            num = num*10+remainder
            x = x//10
        if sign==-1:
            num=(-1)*num
        if num>pow(2,31) or num<pow(-2,31):
            return 0
        return num
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Reverse Integer — அடிக்கடி கேட்கப்படும் கேள்விகள்

Reverse Integer பின்னாலுள்ள intuition என்ன?

Peel digits off the end with % 10 and push them onto a new number with ×10. Handle the sign separately, then reject results outside the signed 32-bit range.

Reverse Integer (LeetCode 7) ஐ எப்படித் தீர்ப்பது?

1. Remember the sign and work with |x|. 2. Repeatedly take the last digit and append it to num. 3. Restore the sign; if outside 32-bit range, return 0.

Reverse Integer இன் time மற்றும் space complexity என்ன?

Time: O(log x). Space: O(1). (Accepted approach: Digit popping.)

Reverse Integer இல் பொதுவான தவறுகள் என்ன?

Overflow check is required: 1534236469 reversed overflows.