LeetCode_Plus One

来源:互联网 发布:民国报刊数据库 编辑:程序博客网 时间:2024/06/15 11:15

一.题目

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 Tags
Have 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必须好好学习啊,了解坑在哪里。



版权所有,欢迎转载,转载请注明出处,谢谢微笑




0 0