zoukankan      html  css  js  c++  java
  • 【leetcode】Plus One (easy)

    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.

    分析:思路是很清晰的,就是从数字最低位开始向上循环,如果是9就变成0,如果不是就直接当前位加1,返回。如果全都是9,就在最高位加一个1.

    但是我写C++的代码比较少,写的时候对于哪里是最高位弄晕了。绕了好久才AC。

    高位在前,就是高位是先压入vector的,那么最高位在digits.begin()。先压入的靠近下标0

    如果需要新加一个最高位,那digits里面肯定都是0,压入1后,最高位变成最后压入的了,所以还需要翻转一下。

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    class Solution {
    public:
        vector<int> plusOne(vector<int> &digits) {
            int i = digits.size() - 1;
            while(i >= 0)
            {
                if(digits[i] == 9)
                {
                    digits[i] = 0;
                    i--;
                }
                else
                {
                    break;
                }
            }
            if(i < 0)
            {
                digits.push_back(1);
                reverse(digits.begin(), digits.end());
            }
            else
            {
                digits[i] += 1;
            }
            
            return digits;
        }
    };
    
    int main()
    {
        Solution s;
        vector<int> in, out;
        in.push_back(1);
        in.push_back(9);
        in.push_back(9);
        out = s.plusOne(in);
    
        return 0;
    }
  • 相关阅读:
    python3.4 + pycharm 环境安装 + pycharm使用
    ddt源码修改:HtmlTestRunner报告依据接口名显示用例名字
    re模块
    LeetCode Weekly Contest 12
    求解强连通分量
    几道题-找规律-记录并查找
    欧几里德算法
    树上二分
    几道题-博弈
    随便写一些东西-缩边
  • 原文地址:https://www.cnblogs.com/dplearning/p/4116384.html
Copyright © 2011-2022 走看看