LeetCode OJ 66. Plus One

时间:2022-06-02 11:53:44

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,长度加一的新数组。代码如下:

 public class Solution {
public int[] plusOne(int[] digits) {
if(digits==null || digits.length==0) return digits;
int i;
for(i = digits.length - 1; i >= 0; i--){
if(digits[i] + 1 < 10){
digits[i] += 1;
break;
}
else digits[i] = 0;
}
if(i < 0){
int[] newdigits = new int[digits.length+1];
newdigits[0] = 1;
return newdigits;
}
return digits;
}
}