Plus One
LeetCode 66 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Carry propagation from the right.
నేను 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
Add 1 to the last digit.
- 2
While there is a carry, add it to the next digit left.
- 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 digitsPlus 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].