LeetCode算法题66解题思路

原题

66. Plus One

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

1
2
3
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

1
2
3
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

解题思路

  1. 要考虑到不需要遍历所有元素,因为当没有进位的时候+1这个行为就结束了;
  2. 要考虑如何处理进位的问题,+1的位置如果产生了进位,那么下一位就要+1,当前位要设为零;
  3. 要考虑到数组的第0个元素也进位了的情况。

把上面三点都照顾到的话,基本就没有问题了。

代码实现

Golang实现

https://github.com/cook-coder/my-leetcode-solution/tree/master/easy/66

成绩

加载评论框需要科学上网