zoukankan      html  css  js  c++  java
  • 【LeetCode】66. Plus One

    题目:

    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.

    提示:

    此题其实是模拟我们在小学时候学习的加法进位的操作。难度不大。

    代码:

    空间复杂度是O(n)的方法:

    class Solution {
    public:
        vector<int> plusOne(vector<int>& digits) {
            int size = digits.size() - 1;
            digits[size] += 1;
            if (digits[size] < 10) {
                return digits;
            }
            vector<int> result;
            for (int i = size; i > 0; --i) {
                if (digits[i] == 10) {
                    digits[i] = 0;
                    digits[i-1] += 1;
                }
            }
            if (digits[0] == 10) {
                result.push_back(1);
                digits[0] = 0;
            }
            for (int i = 0; i <= size; ++i) {
                result.push_back(digits[i]);
            }
            return result;
        }
    };

     空间复杂度是O(1)的方法:

    class Solution {
    public:
        vector<int> plusOne(vector<int>& digits) {
            for (int i = digits.size(); i--; digits[i] = 0)
                if (digits[i]++ < 9) return digits;
            digits[0] = 1;
            digits.push_back(0);
            return digits;
        }
    };
  • 相关阅读:
    url protocol
    wpf webbrowser取消js报错
    c#端口扫描器wpf+socket
    c#协变 抗变
    MTK刷机快捷键
    iTextCharp c#
    wince可用的7-zip
    直播平台搭建与相关资料
    pyinstall
    面向对象常见的术语
  • 原文地址:https://www.cnblogs.com/jdneo/p/4757461.html
Copyright © 2011-2022 走看看