LeetCode | Plus One(數組表示的數字加1)

來源:互聯網
上載者: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,得到結果。跟Add Binary一樣,加上後進位。但容器的話,插入要用insert函數。

class Solution {public:    vector<int> plusOne(vector<int> &digits) {        int len = digits.size();        vector<int> res;        if(len == 0){            res.push_back(1);            return res;        }        int carry = 1;        for(int i = len-1;i >= 0;i--){            int sum = digits[i]+carry;  //先求總和再判斷是否進位            if(sum>=10)                carry = 1;            else                carry = 0;            res.insert(res.begin(),sum%10); //在容器的指定位置插入元素        }        if(carry)            res.insert(res.begin(),1);        return res;    }};

我是重新申請的一個來儲存新值,也可以在未經處理資料基礎上修改。

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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.