public class Solution { public int[] PlusOne(int[] digits) { var last = digits[digits.Length - 1]; if (last + 1 < 10) { digits[digits.Length - 1]++; return digits; } else { var list = new List<int>(); int step = 1; for (int i = digits.Length - 1; i >= 0; i--) { var cur = digits[i]; cur = cur + step; if (cur >= 10) { step = 1; } else { step = 0; } list.Add(cur % 10);//原来肯定是9,9+1变为10 } if (step == 1) { list.Add(1); } list.Reverse(); return list.ToArray(); } } }
https://leetcode.com/problems/plus-one/#/description
补充一个python的实现:
1 class Solution: 2 def plusOne(self, digits: List[int]) -> List[int]: 3 n = len(digits) 4 temp = [0] * n 5 up = 0 6 last = digits[-1] 7 last += 1 8 if last == 10: 9 temp[-1] = 0 10 up = 1 11 else: 12 temp[-1] = last 13 14 for i in range(n-2,-1,-1): 15 cur = digits[i] 16 cur += up 17 if cur == 10: 18 temp[i] = 0 19 up = 1 20 else: 21 temp[i] = cur 22 up = 0 23 if up == 1: 24 temp.insert(0,1) 25 return temp