leetcode 66. 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.

题解:简单的高精度加法,要注意[9]这种输入,要多一位。

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int add=1;
        int n=digits.size();
        stack<int>st;
        vector<int>ans(0);
        while(add){
            if(n==0){
                st.push(1);
                break;
            }
            int t=(digits[n-1]+add)%10;
            add=(digits[n-1]+add)/10;
            st.push(t);
            n--;
        }
        if(n){
            while(n--){
                st.push(digits[n]);
            }
        }
        while(!st.empty()){
            ans.push_back(st.top());
            st.pop();
        }
        return ans;
    }
};

 

posted @ 2016-04-16 23:21  周洋  阅读(389)  评论(0编辑  收藏  举报