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.

 

算法性能:



 

猜你喜欢

转载自logicluo.iteye.com/blog/2238020