LeetCode_Plus One,leetcode_plusone

來源:互聯網
上載者:User

LeetCode_Plus One,leetcode_plusone
一.題目Plus One  Total Accepted: 41858 Total Submissions: 136232My Submissions

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.

Show TagsHave you met this question in a real interview?  Yes No

Discuss





二.解題技巧   這道題只是一道簡單的高精度計算的題,只要從後往前計算即可,同時要用一個變數要儲存低位的進位,如果最高位還有進位的話,就需要在最高位前面添加一位。基本計算過程很簡單,按照上面的做法,時間複雜度為O(n),空間複雜度為O(1)。這裡唯一的技巧就是,由於只是加1計算,因此,如果這一位沒有進位的話,那麼更高位就不需要進行其他處理了,可以直接儲存下來,可以提前退出計算的過程。

三.實現代碼
#include <iostream>#include <vector>#include <algorithm>using namespace std;class Solution{public:    vector<int> plusOne(vector<int> &digits)    {        int Carry = 1;        const int SIZE = digits.size();        int Tmp = 0;        // add one        for (int Index = SIZE - 1; Index >= 0; Index--)        {            Tmp = digits[Index] + Carry;            if (Tmp < 10)            {                Carry = 0;                digits[Index] = Tmp;                break;            }            Carry = 1;            digits[Index] = Tmp - 10;        }        vector<int> Result;        if (Carry == 1)        {            Result.push_back(1);        }        for (int Index = 0; Index < SIZE; Index++)        {            Result.push_back(digits[Index]);        }        return Result;    }};






四.體會    這道題比較簡單,不需要什麼演算法,只是在處理在最高位前面添加一位時,需要利用到一些vector的函數,不過我對ector瞭解得不深,在這裡還踩了一個坑,被標準庫中的copy函數坑了,程式出現了異常的情況,搞了半個小時,才發現是這裡出錯,改成了最簡單的迴圈語句的複製之後,就什麼事都沒有了。STL必須好好學習啊,瞭解坑在哪裡。


著作權,歡迎轉載,轉載請註明出處,謝謝



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.