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.