您的位置:首页 > 其它

【LeetCode】066.Plus One

2015-03-27 16:18 281 查看
题目:

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.
解答:
考虑进位问题,从后往前遍历,低于9直接加上1并且返回,否则一直往前进位。最高位进位后需要新生成一个数组。

代码:

public class Solution {
public int[] plusOne(int[] digits) {
if (digits == null || digits.length == 0)
return null;
int index = digits.length - 1;
while (index >= 0) {
if (digits[index] < 9) {
digits[index] += 1;
return digits;
} else {
digits[index] = 0;
index--;
}
}
int[] ret = new int[digits.length + 1];
if (index < 0) {
ret[0] = 1;
for (int i = 0; i < digits.length; i++) {
ret[i + 1] = digits[i];
}
}
return ret;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: