LeetCode66. 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.

给非负整数的非空数字数组,加上1,并且数组中的每个元素只包含单个数字。

答案

  1. 从后往前判断为9则变0,若全为9则在vector头部插入1
vector plusOne(vector& digits) {
    int num = 0, n = digits.size() - 1;
    while (digits[n] == 9 && n >= 0) {
        digits[n] = 0;
        n--;
    }
    if (n < 0) {
        digits.insert(digits.begin(), 1);
    } else {
        digits[n]++;
    }
    return digits;
}
  1. 试了一下组成数字加一再分解,失败辽

你可能感兴趣的:(LeetCode66. Plus One)