[leetcode] 66.Plus One

来源:互联网 发布:sql为列设置默认值 编辑:程序博客网 时间:2024/05/21 14:47

题目:
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.
题意:
将一个非负的整数按位放在一个数组里,并且最高位在A[0],最低位在A[n-1],比如56,A[0] = 5,A[1] =6;
然后将该数加上一。
思路:
这道题主要需要计算进位,如果最高位产生了进位,那么需要重新开辟一个n+1的数组来存放。

以上。
代码如下:

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