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;
    }
  • 相关阅读:
    如何控制递归的深度
    判断亲密数
    还是鸡兔同笼
    幂之和
    十进制转换成八进制
    单词译码
    笔试考试系统 ____pagelist使用
    笔试考试系统 ____项目部署
    笔试考试系统 ____成绩统计
    笔试考试系统 ____错题查看
  • 原文地址:https://www.cnblogs.com/dplearning/p/4116384.html
Copyright © 2011-2022 走看看