您的位置:首页 > 其它

leetcode66-Plus One(加1问题)

2016-04-17 22:20 344 查看
问题描述:

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.

给定一个以一系列数字表示的非负数,将其加一并转换成数字。

数字存储的最高位在列的最前面。

问题求解:

class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int n=digits.size();
digits[n-1] += 1;//(1)最低位+1
//int carry=0;
for(int i=n-1;i>0;i--)
{
if(digits[i]>=10)
{//(2)诸位比较,如果大于10,则需处理进位
digits[i-1] += digits[i]/10;
digits[i] = digits[i]%10;
}
}
//(3)判断最高位是否大于10
if(digits[0]>=10)
{//若大于10,则开辟一个长度大1的数组存储最后得数
vector<int> d(n+1);
d[0] = digits[0]/10;
digits[0] %= 10;
int k=1, j=0;
while(j<n)
{
d[k++]=digits[j++];
}
return d;
}
return digits;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: