Plus One LeetCode Solution in Python 3.
Given a non empty array of decimal digits representing a non-begative integer.
Increment the integer, most significant digit is on the left. Each element contains a single digit.
No leading zeros except for the number 0.
Examples
- Input: digits = [1,2,3]
- Output: [1,2,4]
- Input array represents the int 123 + 1 = 124
- Input: digits = [9]
- Output: [1,0]
- Input array represents the int 9 + 1 = 10
- Input: digits = [9,9]
- Output: [1,0,0]
- Input array represents the int 99 + 1 = 100
Analysis
One solution is to convert the list elements into int.
Then add 1 and convert back to a list.
Test Code
import time
start_time = time.time()
def main():
print("start")
#digits = [1,2,3]
digits = [9,9]
print ("digits: " + str(digits))
sol = Solution()
result = sol.plusOne(digits)
print("result is: "+ str(result))
print("end")
class Solution:
def plusOne(self, digits: list[int]) -> list[int]:
tmp_int = 0
for i in range(len(digits)):
tmp_int += digits[i] * pow(10, (len(digits)-1-i))
return list(map(lambda x: int(x), str(tmp_int+1)))
if __name__ == "__main__":
main()
print("--- %s ms ---" % int(((time.time() - start_time)*1000)))
Test Output
start
digits: [9, 9]
result is: [1, 0, 0]
end
--- 31 ms ---
>>>
Final Solution Code
class Solution:
def plusOne(self, digits: list[int]) -> list[int]:
tmp_int = 0
for i in range(len(digits)):
tmp_int += digits[i] * pow(10, (len(digits)-1-i))
return list(map(lambda x: int(x), str(tmp_int+1)))
Related Guides and Helpful Resources
If you found this guide helpful, check out these related step-by-step tutorials and category resources on ION HowTo:
- How to Replace AC Remote Batteries with a Ballpoint Pen: Lever out stubborn AAA batteries from deep remote slots without tools.
- Clean USB-C Port with Paper: Simple household trick to clean lint and debris from loose charging ports safely.
- IKEA KOPLA B22 to E27 Socket Converter Guide: Convert older UK bayonet lamp fittings to fit modern screw-in LED bulbs.
- DIY Hacks and Life Solutions: Explore our full collection of tutorials and step-by-step articles in this category.

Leave a Reply Cancel reply