问题描述:
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;
}
};
本文介绍了一种将非负整数以数组形式表示,并在此基础上加一的算法实现。通过遍历数组从低位到高位逐个处理进位,确保结果正确。
604

被折叠的 条评论
为什么被折叠?



