Plus One

##题目

####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.

##解题思路
该题是对用数组表示的数进行加一,每一位的进位最多为1,思路是维护一个进位,对每一位进行加一,然后判断进位,如果有继续到下一位,否则就可以返回了,因为前面不需要计算了。如果最高位进位存在,其必为1,则需要重新开辟一个digit.length+1的空间,其中第一位为1,其余为都为0,因为只是加一操作,其余位一定是0,否则不会进最高位

##算法代码
代码采用JAVA实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
public int[] plusOne(int[] digits) {
if(digits ==null || digits.length==0)
return digits;
int jinwei=1;
for(int i=digits.length-1;i>=0;i--)
{
int digit=(digits[i]+jinwei)%10;
jinwei=(digits[i]+jinwei)/10;
digits[i]=digit;
if(jinwei==0)
return digits;
}
//说明最高位有进位
int[] res=new int[digits.length+1];
res[0]=1;
return res;

}
}

Comments