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;
    }
  • 相关阅读:
    01-Django 简介
    函数及函数的嵌套等
    循环及循环嵌套
    运算符
    if, elif, else及if嵌套
    变量及变量计算和引用
    Python的3种执行方式
    Jmeter设置默认中文启动
    Vysor
    python基础学习(二)
  • 原文地址:https://www.cnblogs.com/dplearning/p/4116384.html
Copyright © 2011-2022 走看看