LeetCode 66. Plus One

来源:互联网 发布:kinetic sand 淘宝 编辑:程序博客网 时间:2024/06/08 04:10

Description

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.

Analysis

最简单的加法进位处理。
由于仅仅+1,要注意随时提前结束运算,当发现不需要进位时,直接返回结果。

Code

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

Appendix

  • Link: https://leetcode.com/problems/plus-one/
  • Run Time: 3ms
0 0
原创粉丝点击