【leetcode刷题笔记】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.


 

题解:模拟即可,用carries代表进位,当carries=1的时候说明下一位上要加上进位,就一直往前进位,直到某一位可以加1不进位,或者已经到最高位。然后判断最高位是否还要向上进位,如果需要,新申请一个digits.length+1的数组,最高位设置为1,放置+1得到的数;否则,直接返回digits。

代码如下:

 1 public class Solution {

 2     public int[] plusOne(int[] digits) {

 3         if(digits == null || digits.length == 0)

 4         {

 5             int[] answer = {1};

 6             return answer;

 7         }

 8         int kepeler = digits.length-1;

 9         int carries = digits[kepeler] == 9?1:0;

10         digits[kepeler] = (digits[kepeler] + 1)%10;

11         kepeler--;

12         

13         while(kepeler >= 0 && carries == 1){

14             int t = digits[kepeler];

15             digits[kepeler] = (digits[kepeler] + carries)%10;

16             carries = (t == 9)?1:0;

17             kepeler--;

18         }

19         

20         if(carries == 1){

21             int[] answer = new int[digits.length+1];

22             answer[0] = 1;

23             System.arraycopy(digits, 0, answer, 1, digits.length);

24             return answer;

25         }

26         else {

27             return digits;

28         }

29     }

30 }

上述代码中23行是java中拷贝数组的函数,5个参数分别是:源数组,源数组拷贝起始位置,目的数组,目的数组拷贝起始位置,源数组需要拷贝的长度。

你可能感兴趣的:(LeetCode)