66. Plus One

来源:互联网 发布:mysql 参数化 编辑:程序博客网 时间:2024/05/16 18:17

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.

本题的思路如下:首先由于原数组进行了加一操作,因此最终的结果数组长度可能为两种,一种是与原数组长度一致,另一种是比原数组长度大一,在开始计算之前我们不能确定最终的结果数组长度为哪一种情况,因此,我首先用一个List数据类型逐一存放数字的值,最终再放入到结果中,个位上的数字比较特殊因为它执行了加一操作,因此需要单独处理,接下来的各个位上的数字都是由数字本身加上进位从而产生对应的数字与进位,代码如下:

List<Integer> resultList = new ArrayList<Integer>();
        // 特殊情况处理
        if(digits == null || digits.length == 0){
            return new int[0];
        }
        
        int result = (digits[digits.length - 1] + 1) % 10;
        int carry = (digits[digits.length - 1] + 1) / 10;
        resultList.add(result);
        for(int i = digits.length - 2; i >= 0; i--){
            result = (digits[i] + carry) % 10;
            resultList.add(result);
            carry = (digits[i] + carry) / 10;
        }
        
        if(carry != 0){
            resultList.add(carry);
        }
        
        int[] resultArr = new int[resultList.size()];
        for(int i = 0; i < resultArr.length; i++){
            resultArr[i] = resultList.get(resultList.size() -1 - i);
        }
        return resultArr;
    }

在这个过程中,我开辟了一个List用来存放运算过程中产生的结果值,这增大了空间复杂度,上述解决方案是一个通用的解法,对于任何两个数相加都可以使用,针对这道只加一的题目,我没有深入挖掘该题具有的独特特征,因此尝试去寻找更为优秀的方法,发现一个非常简洁的解决方法,该方法基于本题特有的特征,对于一个数字与1相加,只有在数字为9的时候才会产生进位,其它时候不会产生进位,这样当我们对于原始数组从后向前处理对应数字的时候,如果遇到没有进位我们就可以将数组返回作为最终结果,当遇到极端情况时(原始数组中所有数字均为9),这时我们需要将数组长度加一,将首位赋值为1即可,其它的位默认为0,代码如下:

public int[] plusOne(int[] digits) {
        // 特殊情况处理
        if(digits == null || digits.length == 0){
            return digits;
        }
        
        for(int i = digits.length - 1; i >= 0; i--){
            if(digits[i] < 9){
                digits[i]++;
                return digits;
            }
            digits[i] = 0;
        }
        
        int[] result = new int[digits.length + 1];
        result[0] = 1;
        return result;
    }

0 0
原创粉丝点击