leetcode #66 in cpp

来源:互联网 发布:竞彩缩水软件 编辑:程序博客网 时间:2024/06/05 19:35

Solution: 

1.start from the tail of the input, and keep adding 1 until we reach the head of the input or the digit + 1 is less than 10. 

2.check if the head >= 10. If so insert an extra 1 to the input.

Code:

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


0 0
原创粉丝点击