[LeetCode 66] Plus One

90 篇文章 0 订阅

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.

代码比较长

1、vector中capacity()和size()返回值是不一样的,size是实际元素个数,capacity是可以容纳的最大元素个数。

2、貌似insert函数用begin作为参数重新使用begin会出现些问题,有空研究一下

class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
    int i,len,temp,carry=0;
	len=digits.size();
	vector<int>::iterator end=digits.end();
	vector<int>::iterator begin=digits.begin();
	vector<int>::iterator itr=end;
	for(i=0;i<len;i++)
	{
		if(itr==end)
		{
		    if(len==1)
		    {
		       temp=*begin+1;
		    	if(temp==10)
		    	{
		    		*begin=0;
	    			digits.insert(begin,1,1);
	    			return digits;
	    		} 
	    		else
	    		{
	    	        *begin=*begin+1;
	    	        return digits;
	         	}
		    }
		    else
		    {
			itr--;
			temp=*itr+1;
			if(temp==10)
			{
				carry=1;
				*itr=0;
				itr--;
			}
			else
			{
				*itr=*itr+1;
			    return digits;
			}
		    }
		}
		else if(itr==begin)
		{
			temp=*itr+carry;
			if(temp==10)
			{
				*itr=0;
				digits.insert(begin,1,1);
			}
			else
			{
				*itr=*itr+carry;
			}
		}
		else
		{
			temp=*itr+carry;
			if(temp==10)
			{
				carry=1;
				*itr=0;
				itr--;
			}
			else
			{
				*itr=*itr+carry;
			    return digits;
			}
		}
	}
	return digits;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值