15算法课程 66. Plus One

来源:互联网 发布:北京编程培训学校 编辑:程序博客网 时间:2024/06/16 05:24


Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.


solution:

一个用数组表示的整数,数组的每一个元素代表这个整数的一位数字,求这个整数加1之后所代表的数组


code:

class Solution {public:    vector<int> plusOne(vector<int>& digits) {        vector<int> result;        int flag = 1;        for (int i = digits.size() - 1; i >= 0; i--) {            if (digits[i] == 9 && flag == 1) {                result.push_back(0);                flag = 1;            }            if (digits[i] != 9 && flag == 1) {                flag = 0;                result.push_back(digits[i] + 1);                continue;            }            if (flag == 0) {                result.push_back(digits[i]);            }        }        if (flag == 1) {            result.push_back(1);        }        reverse(result.begin(), result.end());        return result;    }};


原创粉丝点击