您的位置:首页 > 其它

[leetcode] Plus One

2015-09-13 11:39 330 查看
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.


例如:98,存储为:array[0]=9; array[1]=8。

思路:从数组的最后一位开始加1,需要考虑进位,如果到[0]位之后仍然有进位存在,需要新开一个长度为 digits.length + 1 的数组,拷贝原数组到该数组中。

JAVA代码:

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