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.
public class Solution {
public int[] plusOne(int[] digits) {
for (int i = digits.length-1; i >= 0; i--) {
digits[i] = digits[i]+1;
if (digits[i] == 10) {
digits[i] = 0;
} else {
return digits;
}
}
int[] newdigits = new int[digits.length+1];
newdigits[0] = 1;
for (int i = 1; i < newdigits.length; i++) {
newdigits[i] = digits[i-1];
}
return newdigits;
}
}
本文介绍了一种在给定一个由数字组成的数组表示的非负整数上加一的算法实现。该算法从数组的最低位开始遍历,逐位进行加一操作,并处理进位。如果最高位产生进位,则需要创建一个新的数组来容纳额外的进位值。
408

被折叠的 条评论
为什么被折叠?



