Leetcode Algorithm Practice PlusOne

Source: Internet
Author: User

See today Cool Shell recommended foreign Programming leetcode Algorithmic Programming web site , there are currently 154 algorithms, the feeling is very interesting, ordinary work is also relatively busy, now very little time to exercise algorithm related things, there is a time to calm down the heart, review the foundation, active under the idea of self, is also necessary. in the afternoon, I did a simple question, and then we added some other questions.

1. TopicsGiven a non-negative number represented asAn array of digits, plus one to the number. The digits is stored such , the most significant digit isAt the head of the list.

First of all, explain the topic, the meaning of this question is:

An array is used to represent a non-negative integer, the integer is +1, and the resulting result is represented by an array. This topic has a hypothetical premise: the numbers in the array are in the range of 0-9 (just beginning to confuse, thinking that the number in the array can be any large value, so to solve the problem, it will be very difficult).

2. Analysis

Knowing the premise, this topic is relatively simple, starting from the last one of the array, each bit needs to determine whether to carry, if carry, since set to 0, otherwise self-increment can. Directly attached source :

classSolution { Public: Vector<int> PlusOne (vector<int> &digits) {
intSize =digits.size (); if(Digits[size-1] <9) {digits[size-1] +=1; returndigits; } //If rounding is required BOOLcarry =true; for(inti = size-1; I >=0; I--) { if(!carry) { Break; } if(Digits[i] = =9) {Carry=true; //after rounding, the original position 0Digits[i] =0; if(i = =0) { //after the first digit of the array is rounded, you need to insert a new number firstDigits.insert (Digits.begin (),1); } } Else { //don't carry, you quit.carry =false; Digits[i]+=1; } } returndigits; }};

Leetcode Algorithm Practice PlusOne

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.