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.
题目:
给定一个十进制数,用数组表示每一位,要求返回加一后的结果
思路:
从数组尾部到头部处理,需要判断是否最后要进位,如果要进位需要在vector的最前面插入1.
C++代码如下:
#include<iostream> #include<vector> using namespace std; class Solution { public: vector<int> plusOne(vector<int> &digits) { int size=digits.size()-1; while(size>=0) { if(digits[size]<9) { digits[size]+=1; break; } else { digits[size]=0; size--; } } size++; if(size==0&&digits[size]==0) { digits.insert(digits.begin(),1); } return digits; } void Convert(int num,vector<int> &digits) { if(num>=10) Convert(num/10,digits); digits.push_back(num%10); } }; int main() { vector<int> digits; int num; cin>>num; Solution s; s.Convert(num,digits); for(auto v:digits) cout<<v<<" "; cout<<endl; s.plusOne(digits); for(auto v:digits) cout<<v<<" "; cout<<endl; }
运行结果: