Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 66 · Other

Plus One

LeetCode 66 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Carry propagation from the right.

सोपाArrayMath

मी Plus One (LeetCode 66) असा सोडवला — Other पॅटर्नमधील एक सोपा प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

Add one to the last digit and propagate the carry leftwards. If the carry survives past the first digit (all nines), prepend a 1.

Approach

  1. 1

    Add 1 to the last digit.

  2. 2

    While there is a carry, add it to the next digit left.

  3. 3

    Leftover carry → prepend it.

मी कसा सोडवला

Carry loopPythonO(n) time
class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        carry=0
        n = len(digits)
        last_digit=digits[n-1]
        sum = last_digit+1
        carry = sum//10
        digits[n-1]=sum%10
        r=n-2
        while carry!=0 and r>=0:
            sum = digits[r]+carry
            carry = sum//10
            digits[r]=sum%10
            r-=1
        if carry>0:
            digits=[carry]+digits
        return digits
स्टेप-थ्रू लोड होत आहे…

Plus One — वारंवार विचारले जाणारे प्रश्न

Plus One मागील intuition काय आहे?

Add one to the last digit and propagate the carry leftwards. If the carry survives past the first digit (all nines), prepend a 1.

Plus One (LeetCode 66) कसा सोडवावा?

1. Add 1 to the last digit. 2. While there is a carry, add it to the next digit left. 3. Leftover carry → prepend it.

Plus One ची time आणि space complexity किती आहे?

Time: O(n). Space: O(1) (O(n) when growing). (Accepted approach: Carry loop.)

Plus One मध्ये सामान्य चुका कोणत्या?

[9,9,9] becomes [1,0,0,0].