每周一算法2017.10.27

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)首先获取数组,然后从数组最后一位开始向前检查,如果当前数字是小于9,说明加1无需进位,从循环跳出即可,如果当前数字等于9,说明需要加1并涉及到进位,加1后当前数字应记为0,继续循环处理。

(2)当对数组处理完后,还需要判断当前第0位是不是已经变为0了,如果已经变为0了,需要进位,则在最前头加一个1, 其他则不需要;《一般对数字进行操作的题都要考虑边界,尤其是溢出问题》

或者这样考虑:

将一个数字的每个位上的数字分别存到一个一维向量中,最高位在最开头,我们需要给这个数字加一,即在末尾数字加一,如果末尾数字是9,那么则会有进位问题,而如果前面位上的数字仍为9,则需要继续向前进位。

代码:

java代码:

public class Solution {  
    public static void main(String[] args){
        int a[] = {9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9};
        Solution test = new Solution();
        int b[] = test.arrayHeadOfTheList(a);
    }
    public int[] arrayHeadOfTheList(int[] digits){
        int n = digits.length;
        for (int i = digits.length - 1; i >= 0; --i){
            if (digits[i] < 9) {
                ++digits[i];
                return digits;
            }
            digits[i] = 0;
        }
        int[] res = new int[n + 1];
        res[0] = 1;
        return res;
    }
}

swift代码:

func arrayHeadOfTheList(_ digits:inout [Int]) -> [Int] {  
    var i = digits.count - 1
    while i >= 0 {
        if digits[i] < 9 {
            digits[i] = (digits[i] + 1)
            return digits
        }
        digits[i] = 0
        i -= 1
    }
    digits.insert(1, at: 0)
    return digits
}

本题来自leetcode

comments powered by Disqus