[LeetCode]11. Plus One加一運算

來源:互聯網
上載者:User

標籤:

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:將一個數位每個位上的數字分別存到一個一維向量中,最高位在最開頭。注意這是個大數問題,不能先遍曆以計算出digits所表示的數,然後再加1,最後將其順序放到vector中。

class Solution {public:    vector<int> plusOne(vector<int>& digits) {        vector<int> res;        int n = digits.size();        int carry = 0;        int one = 1;        for(int i = n - 1; i >= 0; i--)        {            int num = digits[i] + one + carry;            one = 0;            carry = num / 10;            res.push_back(num % 10);        }        if(carry)            res.push_back(carry);        reverse(res.begin(), res.end());                return res;    }};

 

解法2:演算法如下:首先判斷最後一位是否為9,若不是,直接加一返回,若是,則該位賦0,再繼續查前一位,同樣的方法,知道查完第一位。如果第一位原本為9,加一後會產生新的一位,那麼最後要做的是,查運算完的第一位是否為0,如果是,則在最前頭加一個1。參考:http://www.cnblogs.com/grandyang/p/4079357.html

class Solution {public:    vector<int> plusOne(vector<int> &digits) {        int n = digits.size();        for (int i = n - 1; i >= 0; --i) {            if (digits[i] == 9) digits[i] = 0;            else {                digits[i] += 1;                return digits;            }        }        if (digits.front() == 0) digits.insert(digits.begin(), 1);        return digits;    }};

[LeetCode]11. Plus One加一運算

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.