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