leetcode-66. Plus One

    xiaoxiao2021-03-25  198

    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.

    需要想明白的地方:进位,循环终止条件,if == 10,还有就是注释那行不应该有

    class Solution { public: vector<int> plusOne(vector<int>& digits) { int n = digits.size(); int carry = 1; for(int i = n-1; i >= 0 && carry; --i){ digits[i]++; if(digits[i] == 10){ digits[i] = 0; carry = 1; } else carry = 0; // digits[i-1] += carry; } if(carry){ digits.insert(digits.begin(), 1); } return digits; } };
    转载请注明原文地址: https://ju.6miu.com/read-657.html

    最新回复(0)