LeetCode 66 _ One Plus 加一 (Easy)

Description:

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

 

 

Solution:

这道题要求我们将所给的数组加一再以原形式返回

 

最近这几天都是Easy,实在是很基础哇,这道题本质就是用我们现实生活中做加法的思路即可。

在做加法的时候,如果最后一位数不为9,即加一后不用进位,那么我们直接将该数+1,即得到了答案。

如果为9,那么就需要考虑进位的问题了。

因为产生了进位,该位必须变为0,然后再检查前面一位,如果为9继续进位,直到得到不为9的位置;或者可能到达了数组的头部仍为9,那么这个就需要将数组扩容了,将扩容的数组首位设置为1,剩下的位已经被变为了0,至此输出即可。

 

 

Code:

public int[] plusOne(int[] digits) {
	int n = digits.length;
	int count = n -1;
	if (digits[n-1] != 9) {
		digits[count]++;
		return digits;
	}else {
		while (digits[count] == 9) {
			if (count == 0) {
				int[] res = new int[n+1];
				res[0] = 1;
				return res;
			}else {
				digits[count] = 0;
				count --;
			}
		}
		digits[count] ++;
	}
	return digits;
}

  

 

 

提交情况:

Runtime: 0 ms, faster than 100.00% of Java online submissions for Plus One.

Memory Usage: 37.2 MB, less than 55.00% of Java online submissions for Plus One.

 

 

LeetCode讨论区有一个写起来更为简洁的方法,思路基本一致,它采用的时遍历的方法,而上面的方法则是层次推进,其实运行的时间空间复杂度也都一样,emmm,总的来说没有什么差距,我们来看一下吧:

public int[] plusOne(int[] digits) {
    int n = digits.length;
    for(int i=n-1; i>=0; i--) {
        if(digits[i] < 9) {
            digits[i]++;
            return digits;
        }
        digits[i] = 0;
    }
    
    int[] newNumber = new int [n+1];
    newNumber[0] = 1;
    
    return newNumber;
}
posted @ 2019-04-07 19:25  Doris7  阅读(112)  评论(0编辑  收藏  举报