LeetCode: Plus One [067]

来源:互联网 发布:淘宝店铺分销 编辑:程序博客网 时间:2024/05/16 01:28

【题目】


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.



【题意】

给定一个非负整数,这个表示为一个数字数组。计算这个整数加1后的值。


【思路】

       

从低位到高位依次相加,注意处理进位。


【代码】

class Solution {public:    vector<int> plusOne(vector<int> &digits) {        vector<int>result;        int size=digits.size();        int val2next=0; //进位值        stack<int> st;  //维护一个栈,用来存放从低到高计算的各位的值        if(size==0){            result.push_back(1);            return result;        }        for(int i=size-1; i>=0; i--){            int sum=digits[i]+val2next;            if(i==size-1)sum+=1;            val2next=sum/10;            st.push(sum%10);        }        if(val2next!=0)st.push(val2next);        while(!st.empty()){            result.push_back(st.top());            st.pop();        }        return result;    }};


0 0
原创粉丝点击