Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 8 · Parsing / Conversion

String to Integer (atoi)

LeetCode 8 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Strip → sign → digits → clamp.

ಮಧ್ಯಮString
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು String to Integer (atoi) (LeetCode 8) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Parsing / Conversion ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Parse like a careful machine: drop whitespace, read an optional sign, then consume digits until a non-digit, and finally clamp to the 32-bit range.

Approach

  1. 1

    Strip spaces; empty → 0.

  2. 2

    Read '+' or '−'.

  3. 3

    Accumulate num = num·10 + digit until a non-digit.

  4. 4

    Apply the sign and clamp to [−2³¹, 2³¹−1].

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Character parserPythonO(n) time · O(1) space
class Solution:
    def myAtoi(self, s: str) -> int:
        #if trailing space ignore
        #if leading space ignore
        #if negative keep
        #if non numeric ignore
        s=s.strip()
        if not s:
            return 0
        sign = 1
        i=0
        if s[0]=="-":
            sign = -1
            i+=1
        elif s[0]=="+":
            i+=1
        n = len(s)
        num=0
        while i<n:
            #not between 0 and 9
            if not (ord(s[i])-ord('0')>=0 and ord(s[i])-ord('0')<=9):
                break
            else:
                num=num*10+ord(s[i])-ord('0') #0+4, 4*10+2
            i+=1
        num=num*sign
        INT_MIN = -2**31
        INT_MAX = 2**31-1
        if num < INT_MIN:
            return INT_MIN
        elif num>INT_MAX:
            return INT_MAX
        return num
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

String to Integer (atoi) — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

String to Integer (atoi) ಹಿಂದಿನ intuition ಏನು?

Parse like a careful machine: drop whitespace, read an optional sign, then consume digits until a non-digit, and finally clamp to the 32-bit range.

String to Integer (atoi) (LeetCode 8) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Strip spaces; empty → 0. 2. Read '+' or '−'. 3. Accumulate num = num·10 + digit until a non-digit. 4. Apply the sign and clamp to [−2³¹, 2³¹−1].

String to Integer (atoi) ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n). Space: O(1). (Accepted approach: Character parser.)

String to Integer (atoi) ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Stop at the first non-digit — 'words 987' is 0. Only one sign character is allowed.