[LeetCode/LintCode] Plus One

linspiration

Problem

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

Given [1,2,3] which represents 123, return [1,2,4].

Given [9,9,9] which represents 999, return [1,0,0,0].

Solution

Update 2018-9

class Solution {
    public int[] plusOne(int[] digits) {
        int n = digits.length;
        for (int i = n-1; i >= 0; i--) {
            if (digits[i] == 9) {
                digits[i] = 0;
            } else {
                digits[i]++;
                return digits;
            }
        }
        int[] res = new int[n+1];
        res[0] = 1;
        return res;
    }
}

进位法:

public class Solution {
    public int[] plusOne(int[] digits) {
        int carry = 1;
        for (int i = digits.length-1; i >= 0; i--) {
            int cur = digits[i] + carry;
            carry = cur / 10;
            digits[i] = cur % 10;
            if (carry == 0) break;
        }
        if (carry == 1) {
            int[] res = new int[digits.length+1];
            res[0] = 1;
            return res;
        }
        return digits;
    }
}

逢9化0法:

public class Solution {
    public int[] plusOne(int[] digits) {
        int last = digits.length-1;
        while (last >= 0 && digits[last] == 9) {
            digits[last] = 0;
            last--;
        }
        if (last == -1) {
            int[] res = new int[digits.length+1];
            res[0] = 1;
            return res;
        }
        else {
            digits[last] += 1;
            return digits;
        }
    }
}

阅读 1.7k

Road to Glory
對酒當歌,人生幾何? 譬如朝露,去日苦多。
161 声望
53 粉丝
0 条评论
你知道吗?

161 声望
53 粉丝
宣传栏