066加一
给定一个非负整数组成的非空数组,在该数的基础上加一,返回一个新的数组。
最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
示例 1:
输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。
示例 2:
输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。
菜鸟
- 最简单的加法法则,两数相加在加上进位即可
- 关于
How to convert List<Integer> to int[] in Java?
点我 - Java8中可以用
int[] array = list.stream().mapToInt(i->i).toArray();
-
Unfortunately, I don’t believe there really is a better way of doing this due to the nature of Java’s handling of primitive types, boxing, arrays and generics. In particular:
List.toArray won’t work because there’s no conversion from Integer to int. You can’t use int as a type argument for generics, so it would have to be an int-specific method (or one which used reflection to do nasty trickery).
I believe there are libraries which have autogenerated versions of this kind of method for all the primitive types (i.e. there’s a template which is copied for each type). It’s ugly, but that’s the way it is I’m afraid :(
Even though the Arrays class came out before generics arrived in Java, it would still have to include all the horrible overloads if it were introduced today (assuming you want to use primitive arrays).From https://stackoverflow.com/questions/960431/how-to-convert-listinteger-to-int-in-java#answer-960449
class Solution {
public int[] plusOne(int[] digits) {
int carry = 1; // 初始化为1,即加一的效果
LinkedList<Integer> list = new LinkedList<Integer>();
for (int i = digits.length - 1; i >= 0; i--) {
list.addFirst((digits[i] + carry) % 10);
carry = (digits[i] + carry) / 10;
}
if (carry > 0) {
list.addFirst(carry);
}
// Integer[] ans = new Integer[list.size()];
// return list.toArray(ans); 返回的是Integer[],而不是int[]对象
int[] ans = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
ans[i] = list.get(i);
}
return ans;
}
}
大神
- 如果末尾为9的话,加一才需要进位,其他情况加一直接返回
- 如果最高位为9,进位为1,则在前面加一位
class Solution {
public int[] plusOne(int[] digits) {
for (int i = digits.length - 1; i >= 0; i--) {
if (digits[i] == 9) {
digits[i] = 0;
} else {
digits[i] += 1;
return digits;
}
}
int[] newArray = new int[digits.length+1];
newArray[0] = 1;
return newArray;
}
}