LeetCode 66 Plus One

来源:互联网 发布:mac软件合集百度云 编辑:程序博客网 时间:2024/06/05 20:36

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.

题意就是:一个十进制数n以位放在数组里面,然后n+1,问数组变成什么样了。如:9999+1=[9,9,9,9]+1=10000=[1,0,0,0]。

代码如下:

public int[] plusOne(int[] digits) {for (int i = digits.length - 1; i >= 0; i--) {if (digits[i] == 9) digits[i] = 0;else {digits[i]++;return digits;}}int[] newDigits = Arrays.copyOf(digits, digits.length + 1);newDigits[0] = 1;newDigits[digits.length] = 0;return newDigits;}


0 0