【Leetcode】之Plus One

本文介绍了一种解决数组形式非负整数加一问题的方法。通过C++实现,从数组最后一位开始计算,遇到进位则更新相应位值。若最高位进位,则在最前面插入1。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.问题描述

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.

二.我的解题思路

本题比较容易,直接把结果vector初始化为digits。然后从最后一位开始计算,如果不需要进位,那么直接return。如果最高位加到最后的结果是大于10的,那么就使用vector的insert方法,在最高位前面插入一个1.测试通过的程序如下:

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
         int len = digits.size();
         vector<int> res(digits.begin(),digits.end());
         if(len==0) return res;
         int flag=1;
         for(int i=len-1;i>=0;i--){
            int curr = digits[i];
            if(curr+flag<10){
                res[i]=curr+flag;
                flag=0;
                return res;
            }
            else{
                res[i]=curr+flag-10;
                flag=1;
            }
        }
        res.insert(res.begin(),1,1);
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值