您的位置:首页 > 其它

LeetCode Plus One

2014-07-21 15:40 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.

将数组表示的数字加1

代码:

class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
vector<int> ans;
int add,carry=1;	//一位的和,进位
int len=digits.size();
for(int i=len-1;i>=0;i--)
{
add=carry;
add+=digits[i];
carry=add/10;
ans.push_back(add%10);
if(carry==0)	//没有进位时直接复制
{
while(--i>=0)
ans.push_back(digits[i]);
}
}
if(carry>=1)
ans.push_back(1);
reverse(ans.begin(),ans.end());
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: