Topic Overview
- Title: buckle force: 66 plus one
- Difficulty: Easy
- content:
Given a non-negative integer nonempty array of integers represented, on the basis of the number plus one.
Most significant digit stored in the first array, each element of the array stores only a single digit.
You may assume that in addition to the integer 0, the integer does not begin with a zero.
Example 1:
Input: [1,2,3] Output: [2,4] Explanation: numeral 123 denotes the input array.
Example 2:
Input: [4,3,2,1] Output: [4,3,2,2] Explanation: input array represents a number 4321.
Source: stay button (LeetCode) link: https: //leetcode-cn.com/problems/plus-one
The first idea
While loop becomes an integer array, and then calculating the num number of digits, then backwards cycle, integer array becomes.
Code
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int num=0;
int i=0;
int a;
for(int i(0);i<digits.size();i++){
num=num*10+digits[i];
}
num++;
while(num/10!=0){
i++;
}
do{
a= num%10;
digits[i]=a;
i--;
num=num/10;
}while(i==0);
return digits;
}
};
Test Submit
analysis
Running time is too long
Improve
Re-organize your thoughts:
total is divided into three cases:
. ① array 9 is not the last one, will not carry the plus one, such as: [1,2,3], plus a still three
. ② array final there are nine, but the first one is not 9, plus a still does not change the number of elements in the array, such as [1,9,9,9]
③. array book 9, add one would add an element, such as [9 , 9,9]
solution:
. ① long time to find reverse circulation 9 becomes 0, until the last one in a row of 9, plus one to the previous one element
② last case instead of the first. element to 0, the last one plus a 0;
Improved Code
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int i=digits.size()-1;
for(i;i>=0;i--){
if(digits[i]==9)
digits[i]=0;
else {
digits[i]++;
break;
};
}
if(digits[0]==0)
{
digits[0]=1;
digits.push_back(0);
}
return digits;
}
};
Improved Submit
Harvest summary
push_back is a programming language function name inside. As the vector c ++ header file push_back which have this function, as added to the tail of vector data in a vector type in effect.