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;
}