[leetcode]Plus One
简单题。进位加法,或者数九就可以了。
public class Solution { public int[] plusOne(int[] digits) { // Start typing your Java solution below // DO NOT write main() function int[] ret = digits; int len = digits.length; if (len == 0) return ret; int i = len - 1; while (i >= 0 && digits[i] == 9) { i--; } if ( i == -1) { ret = new int[len+1]; ret[0] = 1; } else { digits[i]++; for (int j = i+1; j < len; j++) { digits[j] = 0; } } return ret; } }
Python3
class Solution: def plusOne(self, digits: List[int]) -> List[int]: result = digits[:] i = len(digits) - 1 carry = 1 while i >= 0: if carry == 0: break result[i] += carry if result[i] >= 10: carry = 1 result[i] -= 10 else: carry = 0 i -= 1 if carry == 1: result.insert(0, 1) return result