加1 - 简单

*************

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值