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)))
Leave a Reply