Plus One

题目描述
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.

分析:整数型数组的最后一个元素加1,按照十进制操作,如果需要进位的话完成进位即可,并返回加1后的数组。

我的Code如下:

class Solution {
    public int[] plusOne(int[] digits) {
        //如果最后一位小于9,直接末位加1,并返回即可
        if(digits[digits.length-1]<9){
            digits[digits.length-1] = digits[digits.length-1] + 1;
            return digits;
        }
        //数组array1用来倒序存储数组digits
        int[] array1 = new int[digits.length + 1];
        for(int i=0;i<digits.length; i++){
            array1[i] = digits[digits.length - 1 - i];
        }
        //array首位加1,并进行进位操作
        array1[0] = array1[0] + 1;
        for(int i=0; i<digits.length; i++){
            if(array1[i] > 9){
                array1[i] = 0;
                array1[i+1] = array1[i+1] + 1;
            }
        }
        //array2倒序存储array1,此时已经得到正确结果,但是要判断应当输出的数组个数,因为array1,array2,array3的长度大于digits。
        int[] array2 = new int[array1.length];
        for(int i=0; i<array1.length; i++){
            array2[i] = array1[array1.length - 1 -i];
        }
        if(array2[0] == 0){
            for(int i=0; i<digits.length; i++){
                array2[i] = array2[i+1];
            }
            int[] array3 = new int[digits.length];
            for(int i=0; i<digits.length; i++){
                array3[i] = array2[i];
            }
            return array3;    
        }else if(array2[0]>1){
            int[] array3 = new int[digits.length];
            for(int i=0; i<digits.length; i++){
                array3[i] = array2[i];
            }
            return array3;    
        }else{
            return array2;
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Given a non-empty array of digits representing a non-nega...
    烟雨醉尘缘阅读 165评论 0 0
  • Given a non-empty array of digits representing a non-nega...
    花落花开花满天阅读 285评论 0 0
  • Given a non-negative integer represented as a non-empty a...
    ShutLove阅读 251评论 0 0
  • title: Plus Onetags:- plus-one- No.66- simple- stack Prob...
    yangminz阅读 218评论 0 0
  • 山洞里有一个时间隧道,进去的人都到另一个时代里了。个好笑的是有的到了恐龙时代,有的到了外星球…… 我到了恐龙时代有...
    芦嘉钰阅读 115评论 0 1