您的位置:首页 > 其它

leetcode ||66、 Plus One

2015-04-03 09:47 399 查看
problem:

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.

Hide Tags
Array Math

题意,用数组的形式保存一个非负整数,每一位0~9,将该数+1,返回其数组形式,要求最高位数在数组首位

thinking:

(1)首先要读懂题意,这题不难。

(2)注意细节:

1、

while(a>0 && --i>=0)
{
int tmp=digits[i];
digits[i]=(digits[i]+a)%10;
a=(tmp+a)/10;
}
临时变量的应用

2、最后一位要不要进位,要考虑的到

code:

class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int a=0;
if(digits.size()==0)
{
digits.push_back(1);
return digits;
}
int i=digits.size()-1;
a=( digits[i]+1)/10;
digits[i]=( digits[i]+1)%10;
while(a>0 && --i>=0) { int tmp=digits[i]; digits[i]=(digits[i]+a)%10; a=(tmp+a)/10; }
if(a>0)
digits.insert(digits.begin(),a);

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