首页 > 技术文章 > leetcode 66. Plus One(高精度加法)

zywscq 2016-04-16 23:21 原文

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;
    }
};

 

推荐阅读