zoukankan      html  css  js  c++  java
  • HappyLeetcode44:Plus One

    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增大空间。这个需要用到vector中的insert。这个还是头一次用到,感觉不错。

    代码奉上:

    class Solution {
    public:
        vector<int> plusOne(vector<int> &digits) {
            int value=digits.size()-1;//设置长度
            while(value>=0)
            {
                if(digits[value]<9)
                {
                    digits[value]+=1;
                    break;
                }
                else
                {
                    digits[value]=0;
                    value--;
                }
            }
            value++;
            if(value==0&&digits[value]==0)
            {
                digits.insert(digits.begin(),1);//这句话十分关键
            }
            return digits;
        }
    };
    说一说vector对象中insert的使用方法:vector向量容器中使用insert()方法,可以在vector对象的任意位置前插入一个新的元素,书上说,insert()方法要求插入的位置,是元素迭代器的位置,而不是元素的下标。如上面代码中实在digits.begin()处增添了新的元素。
  • 相关阅读:
    vim配置文件
    NGUI屏幕自适应解决方案
    配置java环境
    Ignore files which are already versioned
    Unity3D TestTool Part _1
    c# 语法
    Application.persistentDataPath 的一个小坑
    Unity3D Log 收集机制
    Android 问题流水总结
    Open Phone, SMS, Email, Skype and Browser apps of Android in Unity3d
  • 原文地址:https://www.cnblogs.com/chengxuyuanxiaowang/p/4220406.html
Copyright © 2011-2022 走看看