[leetcode] 66. Plus One

66. Plus One

Description

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

Analysis

题目第一遍没看懂…在看了例子之后才明白,就是一个简单的+1操作,注意某位是9的话,就要向前进位。
印象深的一个操作是,vector可以在初始化时直接定义数组的元素个数,并把每个元素初始化为0。这个操作在这里非常方便。这样的话如果输入一个整数999,可再初始化一个新的vector数组new_digits,定义它的元素个数为digits.size()+1,这时它会默认把所有元素赋值为0,然后再new_digits[0]=1即可。

例:
vector ilist4(7);
默认值初始化,ilist4中将包含7个元素,每个元素进行缺省的值初始化,对于int,也就是被赋值为0,因此ilist4被初始化为包含7个0。当程序运行初期元素大致数量可预知,而元素的值需要动态获取的时候,可采用这种初始化方式。

另外,不知道for循环和while循环的效率哪个更好,我用的while,代码不变提交了n次发现有时是0ms,有时是4ms。看网上0ms的sample用的for,其他没有变化很大的。

震惊...不过再提交一遍又变成4ms了

Code

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        if(digits.size()==1 && digits[0]==0){
            digits[0] = 1;
            return digits;
        }
        
        int i = digits.size()-1;
        while(i>=0){
            if(digits[i]<9){
                digits[i] += 1;
                return digits;
            }
            else{
                digits[i] = 0;
                i--;
            }
        }
        
        vector<int> new_digits(digits.size()+1);
        new_digits[0] = 1;

        return new_digits;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值