加一 Plus One

目录

  • 题目描述
  • 类型转换
    • Python
  • 倒序遍历
    • C++

题目描述

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

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

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

Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

类型转换

将数组转换为整数,加一后,再变为数组。

Python

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        size=len(digits)
        num=0
        for i in range(size):
            num += digits[i]*10**(size-i-1)
        return [int(x) for x in str(num+1)]

倒序遍历

模拟十进制加法器:首先看加一后是否进位(digits[i]是否为9),不进位的话加一后返回,进位的话,看进位位置,若不是最高位,直接变为0,若是最高位,则变为1,后面填一个0.

C++


```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;
            }
            else if(i==0)
            {
                digits[i]=1;
                digits.push_back(0);
            }
            else
            {
                digits[i]=0;
            }
        }
        return digits;
    }
};

你可能感兴趣的:(数据结构与算法,leetcode)