Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 66 · Other

Plus One

LeetCode 66 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Carry propagation from the right.

ಸುಲಭArrayMath
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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].