zoukankan      html  css  js  c++  java
  • [Leetcode] Plus One

    Plus One 题解

    题目来源:https://leetcode.com/problems/plus-one/description/


    Description

    Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

    You may assume the integer do not contain any leading zero, except the number 0 itself.

    The digits are stored such that the most significant digit is at the head of the list.

    Solution

    class Solution {
    public:
        vector<int> plusOne(vector<int>& digits) {
            int size = digits.size();
            for (int i = size - 1; i >= 0; i--) {
                if (digits[i] < 9) {
                    digits[i]++;
                    return digits;
                }
                digits[i] = 0;
            }
            vector<int> res(size + 1, 0);
            res[0] = 1;
            return res;
        }
    };
    
    

    解题描述

    这道题题意是,给出一个数组代表一个十进制数,高位排在前面,求将这个数加1后的结果同样的数组表示。

    这里关键就是关于进位的问题,而进位只有在数位是9的时候才会发生,因此只需要从低位向高位扫描

    • 出现小于9的数字直接自增数位,返回原数组
    • 否则则将数位置为0继续扫描。
    • 如果扫描完毕没有返回,说明最高位需要补上1,则新建一个数组,最高位设为1,低位全为0即可。
  • 相关阅读:
    React 构建方法总结
    集思广益 (一)
    C#方法调用
    C# Hello World 实例
    C# 环境
    C# 简介
    对象类型的本地写入---plist文件创建以及读取
    正则判断 手机邮箱的正确格式
    数组去重
    Base64编码
  • 原文地址:https://www.cnblogs.com/yanhewu/p/8409267.html
Copyright © 2011-2022 走看看