LeetCode66. Plus One

来源:互联网 发布:亚麻籽粉 知乎 编辑:程序博客网 时间:2024/06/03 21:41

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.

#include<vector>#include<iostream>using namespace std;class Solution {public:    vector<int> plusOne(vector<int>& digits) {        int n=digits.size();        if(n==0){            digits.push_back(1);            return digits;        }        else{            for(int i=n-1;i>-1;--i){                if(digits[i]<9){                    digits[i]=digits[i]+1;                    return digits;                }                else{                    digits[i]=0;                    if(i==0){                       digits.insert(digits.begin(),1);                    }                }            }            return digits;        }           }};void main(){    vector<int> v;    v.push_back(2);    v.push_back(4);    v.push_back(9);    v.push_back(3);    v.push_back(9);    Solution So;    vector<int> res=So.plusOne(v);    int n=res.size();    for(int i=0;i<n;++i){        cout<<res[i]<<" ";    }}

这里写图片描述

0 0
原创粉丝点击