def plusOne(digits): num = 0 for i in range(len(digits)): num += digits[i] * pow(10, (len(digits)-1-i)) return [int(i) for i in str(num+1)]
We're given a list of digits, and the idea here is to convert that list to an integer, num. So each digit is multiplied by the proper place value and added to num. For example, if digits = [3, 8, 2, 5] then on the first iteration 3 is multiplied by 10 to the power of 4-1-0 = 3, so this results in 3000, which is added to num. Then 8 is multiplied by 10^2 and added to num, and so on.
The last step is to add 1 to num, convert it to a list and return that list.
def plusOne(self, digits): num=reduce(lambda x,y:x*10+y,nums)+1 return [int(i) for i in str(num)]
This maybe better！
Sorry, I made a mistake. I thought python had a limit on int, but it is removed now.
If I'm not mistaken, it has been like that for over 13 years. Did you use Python before that?
(I didn't, I've only been using Python for a few years, so for me its ints have "always" been like that)
No, I am new to python. I thought python would be similar to c or java with limitation for int.
def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ nums = reduce(lambda x,y:x*10+y,digits)+1 return [int(i) for i in str(nums)]
good answer, but I think you may change the name "nums" to "digits".
Here is another solution which uses only addition operation and a loop.
def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ length = len(digits) for i in range(length-1, -1, -1): num = digits[i] + 1 if num > 9: digits[i] = 0 if i == 0: digits =  + digits else: digits[i] += 1 break return digits
Here's my solution:
def plusOne(self, digits): for i in range(len(digits)-1, -1, -1): a = (digits[i]+1) // 10 digits[i] = (digits[i]+1) % 10 if a == 0: return digits if a == 1: digits.insert(0, 1) return digits
Thanks @ShawnY Could you explain how num = num*10 + digits[i] would work? The above explanation with pow() makes sense to me. I'm trying to understand your solution. Thanks.
@aelk but have you considered numeric overflow just as the length of digits(
len(digits)) can be very large,so your num may be infinity,that's not good news if you num become infinity .
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.