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;
}

转载于:https://www.cnblogs.com/zingg7/p/10666613.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值