//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.
//使用数组模拟加一
public class Main {
public static void main(String[] args){
System.out.println(plusOne(new int[]{1,9}));
}
public static int[] plusOne(int[] digits) {
int carry = 1;
for(int i = digits.length-1;i>=0;i--){
int val = digits[i]+1;
carry = val/10; //是否有进位
digits[i] = val%10; //当前数字加一后是多少
if(carry == 0){ //如果没有进位就直接返回
return digits;
}
}
if(carry == 1){ //如果增加了以为就新建数组使最高位为1
int[] result1 = new int[digits.length+1];
result1[0] = 1;
return result1;
}else{
return digits; //否则返回digits
}
}
}Leetcode 66. Plus One
最新推荐文章于 2025-10-15 15:56:49 发布

2378

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



