LeetCode (14) Plus One, leetcodeplus

Source: Internet
Author: User

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;    }};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.