LeetCode—Plus One

来源:互联网 发布:大宗师源码 编辑:程序博客网 时间:2024/06/06 11:52

Question:

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.

Example:

input :[19] output [2,0]
input[1,0] output [1,1]
input[99] output[10,0]

Ideas:

数组的遍历需要从右向左进行,然后结果存在临时数组中为从左向右。最后将数组反序

public class Solution {    public int[] plusOne(int[] digits) {        int len = 0;        //因为数组要初始化长度,长度应该为digits中数字长度+1,预留单个数字进位        for(int i=0;i<digits.length;i++){            len+=(digits[i]+"").length();        }        int[] tempArry = new int[(len+1)];        int k = 0;        int carry = 1;//进位        //数组是从左向右开始(0,len-1),但此处需要从最右开始加1,然后再判断是否有进位。        for(int i=digits.length-1;i>=0;i--){            int temp = digits[i]+carry;            tempArry[k] = temp%10;            k++;            carry = temp/10;        }        //如果最左边一位仍有进位,则将进位保存        if(carry != 0){            tempArry[k] = carry;            k++;        }        //根据实际长度,新建数组,并将tempArry数组反序输入到result中。        int[] result = new int[k];        int m=k;        for(int j=0;j<k;j++){            result[--m] = tempArry[j];        }        return result;    }}
0 0
原创粉丝点击