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必須好好學習啊,瞭解坑在哪裡。
著作權,歡迎轉載,轉載請註明出處,謝謝