Leetcode:plus One (plus) "Interview algorithm" __ algorithm

Source: Internet
Author: User

Title: Given A number represented as an array of digits, plus one to the number.

Test instructions Dynamic array saves a number of single digits, forming a large number, and calculating the value after the large number plus one.


Simulates the addition of large numbers, which can be ejected when there is no carry.

Special consideration of each single digit is 9 of the situation, plus one more, that is, the result is 1 plus len a 0,len is the length of digits.

Class Solution {public
:
    vector<int> plusone (vector<int> &digits) {
        int i,p,temp,len= Digits.size ();
        for (I=0;i<len;++i)
        {
            if (digits[i]!=9) break;
        }
        if (I==len)
        {
            vector<int>result;
            Result.push_back (1);
            for (i=0;i<len;++i) result.push_back (0);
            return result;
        }
        Digits[len-1]+=1;
        P=0;
        for (i=len-1;i>=0;--i)
        {
            temp=digits[i]+p;
            digits[i]=temp%10;
            P=TEMP/10;
            if (p==0) break;
        }
        return digits;
    }
;
http://blog.csdn.net/havenoidea/


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.