您的位置:首页 > 其它

【LEETCODE】66-Plus One

2015-12-16 18:06 288 查看
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.

参考: http://blog.csdn.net/fly_yr/article/details/47752855 该题目要求:将一整数按位存储在vector中,对其实现+1操作,返回结果。

是一道简单题目,对存储序列vector中元素,倒序遍历,末位+1,若<10可直接返回,否则,保存进位加之到下一位,循环至最高位。

若此时,进位依然为1,则新建长度增一的vector首位为1,其余为0,返回即可。
http://www.cnblogs.com/ganganloveu/p/4154460.html
从个位数字往前扫,只要一个数字不产生进位,即可加1返回。

如果直到最高位仍有进位,则在数组头部插入1,结果为100…0

解法一:

inplace但插入操作时会产生数组的移位
解法二:
inplace且数组不用移位
http://www.cnblogs.com/zuoyuan/p/3772727.html
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
flag=1

for i in range(len(digits)-1,-1,-1):
if digits[i]+flag==10:        #=10时,此位为0,flag记为1
digits[i]=0
flag=1
else:
digits[i]+=flag           #不是10时,此位+flag,flag记为0
flag=0

if flag==1:                       #首位+flag为10,则在首位补0
digits.insert(0,1)

return digits
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: