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].