66. Plus One
题目:
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
链接: http://leetcode.com/problems/plus-one/
一刷,从最末尾加一,判断进位是否为0,0的时候不需要往前再进位,直接返回,否则继续向前计算。要注意的是
1. idx - 1否则下标过界
2. python swap two variables的trick: https://docs.python.org/2/reference/expressions.html#evaluation-order, http://stackoverflow.com/a/14836456
3. 最后一步还是要判断是否进位为1,不要光想着特殊情况忘记一般情况
4. python list.insert(index, value)两个输入变量的位置不要记错
class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ if not digits: return digits carry = 1 for idx in range(len(digits), 0, -1): carry, digits[idx - 1] = (carry + digits[idx - 1]) / 10, (carry + digits[idx - 1]) % 10 if not carry: return digits if carry: digits.insert(0, carry) return digits
2/12/2017, Java
错误:
1. i需要定义在循环体外面(或者用carry判断,i正常位置即可)
2. Java把int array默认初始化为0.
1 public class Solution { 2 public int[] plusOne(int[] digits) { 3 int carry = 1; 4 int sum = 0; 5 int i; 6 7 for(i = digits.length - 1; i >= 0; i--) { 8 sum = digits[i] + carry; 9 if (sum == 10) { 10 carry = 1; 11 digits[i] = 0; 12 } else { 13 carry = 0; 14 digits[i] = sum; 15 break; 16 } 17 } 18 if (i < 0) { 19 int[] ret = new int[digits.length + 1]; // good to know, Java initialize here to 0. 20 ret[0] = 1; 21 return ret; 22 } 23 return digits; 24 } 25 }