您的位置:首页 > 其它

leetcode解题方案--066--Plus One

2017-12-06 00:34 309 查看

题目

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

分析

数组的末尾加1

考虑进位数组长度也有可能变

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