【leetcode c++】66 Plus One

Plus One

Given a non-negative number represented asan array of digits, plus one to the number.

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

 

一個數字按位存放在一個數組中。我們現在來給這個數字【加1】。

數據結構作業做過鏈表的多項式加減乘除吧,這個只要【加1】而已,不要慌。此題不難。

有兩個坑:第一,進位要處理完善。第二,進位有可能會使位數會變長,需要做插入操作。

 

Leetcode的AcceptedSolutions Runtime Distribution(15-06-26)發現58跟66截圖是同一張,重新截了

 

源碼:(VS2013)

vector<int> plusOne(vector<int>& digits){
	vector<int>::iterator iter = digits.end();
	iter--;
	*iter += 1;

	bool carry = false;
	if (10 == *iter)
	{
		carry = true;
		*iter = 0;
	}
	while (iter != digits.begin())
	{
		iter--;
		if (carry)
		{
			*iter += 1;
			if(10 != *iter) carry = false;
			else *iter = 0;
		}
	}
	if (carry)
	{
		digits.insert(digits.begin(),1);
	}

	return digits;
}


發佈了44 篇原創文章 · 獲贊 4 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章