Plus One 解答

Question

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.

Solution

To solve this problem, we can use a flag to mark if the current digit needs to be changed.

Time complexity O(n), space cost O(n)

 public class Solution {
public int[] plusOne(int[] digits) {
int length = digits.length;
int[] result = new int[length + 1];
int flag = 1;
for (int i = length - 1; i >= 0; i--) {
if (flag == 1) {
if (digits[i] < 9) {
digits[i] += 1;
flag = 0;
} else {
digits[i] = 0;
}
}
}
if (flag == 1) {
for (int i = 0; i < length; i++)
result[i + 1] = digits[i];
result[0] = 1;
return result;
}
return digits;
}
}
上一篇:[Raobin] Ext.net在前端直接将对象转为json形式传入后台


下一篇:cordova启动页面和图标的设置