LeetCode: 66. Plus One

来源:互联网 发布:百度云总显示网络异常 编辑:程序博客网 时间:2024/06/05 07:37

LeetCode: 66. Plus One

题目描述

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.

题目大意: 给定一个用数组存的大数, 计算它加一之后的值。

解题思路

直接按照小学计算两个数的加法的方法模拟。

AC代码

class Solution {public:    vector<int> plusOne(vector<int>& digits) {        reverse(digits.begin(), digits.end());        int carryNum = 1;        for(size_t i = 0; i < digits.size(); ++i)        {            digits[i] += carryNum;            carryNum = digits[i] / 10;            digits[i] %= 10;        }        if(carryNum != 0) digits.push_back(carryNum);        reverse(digits.begin(), digits.end());        return digits;    }};
原创粉丝点击