leetcode 66. Plus One

来源:互联网 发布:南音吉他小屋 淘宝 编辑:程序博客网 时间:2024/06/07 02:39

66. Plus One

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

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

The digits are stored such that the most significant digit is at the head of the list.

只能一位一位处理,不能全部提出来


class Solution {public:    vector<int> plusOne(vector<int>& dig)     {        int flag = 0;            int pos = dig.size();               while (   (--pos) >= 0  )        {            if (pos == dig.size() - 1)            {                if (dig[pos] < 9)                 {                        dig[pos]++;                    return dig;                }                else                {                    dig[pos] = 0;                     flag = 1;                 }            }            else            {                if (dig[pos] + flag < 10)                {                    dig[pos]++;                     return dig;                 }                else                    dig[pos] = 0;            }       }              if (flag==1)       {            dig.insert(dig.begin(), 1);       }       return dig;       }};


原创粉丝点击