LeetCode (14) Plus One, leetcodeplus
Description
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.
Use a string to represent a number. Add 1 to the number and return the result string. The order of numbers is the same as that we usually see.
This question is relatively simple. It should be noted that during the addition operation, every 10 times goes into one place.
- When the decimal digit is not 9, 1 is directly added to the decimal digit. Other digits do not need to be changed.
- If the percentile is 9, traverse to find the first 9 in a row from right to left, add 1 to the first digit of this bit, and then change 9 to 0.
class Solution {public: vector<int> plusOne(vector<int> &digits) { int size = digits.size(); int i = size - 1; while (digits[i] == 9 && i > -1) { i--; } if (i == size - 1) { vector<int> r(digits.begin(), digits.end()); r[i]++; return r; } vector<int> r; if (i == -1) { r.push_back(1); for (int j = 0; j != size; ++j) r.push_back(0); } else{ for (int j = 0; j != i; ++j) r.push_back(digits[j]); r.push_back(digits[i] + 1); for (int j = i + 1; j != size; ++j) r.push_back(0); } return r; }};