(LeetCode OJ) Plus One [66]
66. Plus One
My Submissions QuestionTotal Accepted: 77253 Total Submissions: 242942 Difficulty: Easy
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.
Subscribe to see which companies asked this question
Hide Tags Array Math Show Similar Problems
// First clear the train of thought: the question is that an array is used to represent a non-negative integer, and each bit of the number is stored in the array. // it is clear that the end of the array is the second bit of the number, the start is the highest bit // if the low position is less than 9, it is obvious that it can be directly + 1 // if it is = 9, then the position is zero and the last two digits + 1, similarly, if the value is smaller than 9, it is directly + 1 if it is smaller than 9. Otherwise, it is carried to the front of the array. // an extreme case: for example, 999, after the carry is 1000, the class Solution {public: vector is extended.
PlusOne (vector
& Digits) {vector
Ans = digits; int I = 0; for (I = ans. size ()-1; I> = 0; I --) // The traversal starts from the low position, and the reverse traversal {if (I = 0 & ans [0] = 9) {// processing extreme cases ans [I] = 0; vector
: Iterator ansiter = ans. begin (); ans. insert (ansiter, 1); break;} if (ans [I]! = 9) {ans [I] + = 1; break;} else {ans [I] = 0 ;}} return ans ;}};
Dirty performance ...............................