一、题目
英文:Plus One
中文:加一
二、内容要求
英文: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。 简单的大数加法,遍历数组的每位,同时处理进位,如果最后还有进位,则在数组最前面在插入1即可。
三、代码
java代码
public int[] plusOne(int[] digits) {
int n = digits.length;//求数组长度
for(int i=n-1; i>=0; i--) {//从数组的尾部向头部遍历
if(digits[i] < 9) {//碰到第一个小于9的数,对其加一,并退出循环
digits[i]++;
return digits;
}
digits[i] = 0;//每位均为9时,则将此位设置为0。直到有不为9的位数
}
int[] newNumber = new int [n+1];//否则创建一个新的数组。数组大小加1
newNumber[0] = 1;//最高位为1,其余默认为0
return newNumber;//返回此新的数组
}