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.
【思路】
数组从后往前遍历,加一如果不需要进位的话直接返回加一后的结果,需要进位的话继续向前遍历。如果最前面一位需要进位,则生成一个第一位为1,其他位为0,长度加一的新数组。代码如下:
1 public class Solution { 2 public int[] plusOne(int[] digits) { 3 if(digits==null || digits.length==0) return digits; 4 int i; 5 for(i = digits.length - 1; i >= 0; i--){ 6 if(digits[i] + 1 < 10){ 7 digits[i] += 1; 8 break; 9 } 10 else digits[i] = 0; 11 } 12 if(i < 0){ 13 int[] newdigits = new int[digits.length+1]; 14 newdigits[0] = 1; 15 return newdigits; 16 } 17 return digits; 18 } 19 }