Leetcode-66-Plus One

Plus One

 

来自 <https://leetcode.com/problems/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. 假如数组元素为[1,2,1,0],则只需在数组的最后一个元素上做加1运算即可,即[1,2,1,1].
  2. 如果数组元素的组后一位是9,则在做加1运算时,须将末尾置0,倒数第二位做加1运算。例如数组元素为[1,2,3,9],做加1运算后为[1,2,4,0]
  3. 如果数组中所有的元素都为9,则需要额外申请空间。例如数组元素为[9,9,9],做加1运算之后的结果为[1,0,0,0]

java代码:

public class Solution {
    public int[] plusOne(int[] digits) {
        int carry = 1;
		for (int i=digits.length-1; i >=0; i--) {
			if((digits[i] +carry) <= 9) {
				digits[i] += 1;
				carry = 0;
				break;
			} else {
				digits[i] =0;
				carry = 1;
			}			
		}
		if(carry == 1) {
			int[] newDigits = new int[digits.length + 1];
			newDigits[0] = 1;
			for (int j=0; j<digits.length; j++) {
				newDigits[j+1] = digits[j];
			}
			return newDigits;
		}
        return digits;
    }
}

 代码解读:

Carry 作为加1 的进位,初始值必须为1.

 

算法性能:



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值