当前位置: 首页 > 文档资料 > LeetCode 题解 >

Array - Plus One

优质
小牛编辑
132浏览
2023-12-01

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.

这道题目很简单,就是考的加法进位问题。直接上代码:

  1. class Solution {
  2. public:
  3. vector<int> plusOne(vector<int> &digits) {
  4. vector<int> res(digits.size(), 0);
  5. int sum = 0;
  6. int one = 1;
  7. for(int i = digits.size() - 1; i >= 0; i--) {
  8. sum = one + digits[i];
  9. one = sum / 10;
  10. res[i] = sum % 10;
  11. }
  12. if(one > 0) {
  13. res.insert(res.begin(), one);
  14. }
  15. return res;
  16. }
  17. };