https://oj.leetcode.com/problems/plus-one/
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 int[] plusOne(int[] digits)
Leetcode经常会出现这种题----休闲题,简单的让你充满自信而不被Median of two sorted arrays或者Scramble String这样的题给折磨晕。。。。
这题也是很简单的,注意进位就好。另外也注意一下代码里关于System.arraycopy()的运用:
public int[] plusOne(int[] digits) {
int next = 1;
for(int i = digits.length - 1; i >= 0 && next == 1; i--){
digits[i] += next;
next = digits[i] / 10;
digits[i] %= 10;
}
if(next == 1){
int[] res = new int[digits.length + 1];
System.arraycopy(digits, 0, res, 1, digits.length);//System.arraycopy(Object src, int srcpos, Object dest, int destpos, int length)
res[0] = 1;
return res;
}else
return digits;
}一旦出现了最高位进位的需要,就只能开一个新的空间来放答案了。注意一下System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
这个函数的实现是在底层native端的,比一个个拷贝复制要快速的多。
另外注意一下这个函数的参数,你会发现其实在Java里数组[]也是Object的一种继承。
本文提供了一种解决LeetCode上“加一”问题的方法。该问题要求在数字的数组表示上加一,并考虑进位的情况。解决方案展示了如何通过遍历数组并利用System.arraycopy()进行高效的数据复制。
192

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



