leetcode66: Plus One

来源:互联网 发布:java md5加密解密 编辑:程序博客网 时间:2024/06/09 19:19

要求: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.

例如:输入arr=[9 ,9]  输出[1, 0, 0]      输入[1, 2]   输出[1, 3]

思路:很简单,从最高位开始遍历数组,如果某一位判断大于10;那么这一位清零比它低的那位加一。注意,考虑只有一位这个情况,由于arry[0]这一位是最后单独进行判断的,所以如果只有一位需要另外考虑。 假设arry[0]也发生了进位,那么需要用一个新的数组来返回结果,新数组长度为原数组长度加一,新数组的arr[0]位为1,arr[1]位为0。

public int[] plusOne(int[] digits) {int l = digits.length;int[] arr = new int[l + 1];if (l == 1) {digits[0] += 1;} else {digits[l - 1]++;for (int i = l - 1; i > 0; i--) {if (digits[i] >= 10) {digits[i] = 0;digits[i - 1]++;}}}if (digits[0] == 10) {digits[0] = 0;for (int j = 0; j < l; j++)arr[j + 1] = digits[j];arr[0] = 1;return arr;} elsereturn digits;}


0 0
原创粉丝点击