*************
C++
topic:66. 加一 - 力扣(LeetCode)
*************
The topic is really weird.
![]() |
I have a really smart thought that nums[n] = nums[n] + 1.
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int n = digits.size();
digits[n - 1] = digits[n - 1] + 1;
return digits;
}
};
![]() |
Opps. When the last number is 9, occures error.
Take the last number is 9 as a cinsideration, if digits[n - 1] == 9, digits[n - 1] == 0 and digits[n - 2] ++.
make a loop, stert fron the last of the digits.
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int n = digits.size();
for (int i = n - 1; i >= 0; --i)
{
if (digits[i] == 9)
{
digits[i] = 0;
}
else
{
digits[i]++;
return digits;
}
}
return digits;
}
};
![]() |
In this case should add 1 in the first memory place,
digits.insert(digits.begin(), 1);
它的作用是在名为digits的容器中的开头插入一个值为1的元素。这句代码的语法如下:
- digits.begin()是容器digits的迭代器,表示容器中第一个元素的位置。
- insert()是容器类的成员函数,用于在指定位置插入一个元素。
- (digits.begin(), 1)表示要在容器的开始位置插入值为1的元素。
综合起来,这句代码的逻辑是在名为digits的容器的开头位置插入一个值为1的元素。
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int n = digits.size();
for (int i = n - 1; i >= 0; --i)
{
if (digits[i] == 9)
{
digits[i] = 0;
}
else
{
digits[i]++;
return digits;
}
}
digits.insert(digits.begin(), 1);
return digits;
}
};
This topic has nothing special to tell. Like decimalism in calculator, maybe this is the algorythm for. Code is travelling all the arrangements. Tell the computer how to arrange is the soul.