题目要求:
给定一个非常大的整数,返回它加一后的结果。
Problem Description:
You are given a large integer represented as an integer array digits
, where each digits[i]
is the ith
digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0
's.
Increment the large integer by one and return the resulting array of digits.
思路:
暴力法,先反转,在第一位加1后遍历一遍数组判断是否需要进位,注意最后一位需要判断是否需要多一位1。
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits = digits[::-1]
flag = 0
for i in range(0, len(digits)):
if i == 0:
digits[i] = digits[i] + 1
if digits[i] > 9:
digits[i] = digits[i] - 10
flag = 1
else:
if flag == 0:
continue
if flag == 1:
digits[i] = digits[i] + 1
if digits[i] > 9:
digits[i] = digits[i] - 10
else:
flag = 0
if flag == 1:
digits.append(1)
digits = digits[::-1]
return digits
结果如下: