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;
    }
  • 相关阅读:
    Flink Task 并行度
    flink笔记(三) flink架构及运行方式
    Flink笔记(二) DataStream Operator(数据流操作)
    poj 1463 Strategic game
    2014年3月29日小记
    AC自动机学习
    hdu 1028 Ignatius and the Princess III
    hdu 1542 Atlantis
    hdu 1575 Tr A
    hdu 4193 Non-negative Partial Sums
  • 原文地址:https://www.cnblogs.com/dplearning/p/4116384.html
Copyright © 2011-2022 走看看