66. Plus One

来源:互联网 发布:软件测试实战项目 编辑:程序博客网 时间:2024/05/20 20:56

Task:

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.

Some Questions:

 Is there leading zeros in the number?

What's the length of the number?

Is there fractional part in the number?

Solution:

To solve this problem, my idea is to simulate the process of manual calculation. Add one to the least significant digit, if carry occurs, add one to the second least significant digit, see whether carry occurs, and so on, until carry doesn't occur.

This algorithm runs in O(length of the number) time complexity and O(1) space complexity.

Code:

class Solution {public:    vector<int> plusOne(vector<int>& dig) {        int i;        int len=dig.size();        dig[len-1]++;//add one to the least significant digit        for(i=dig.size()-1;i>0;i--)//deal carry except the most significant digit        {            dig[i-1]+=dig[i]/10;            dig[i]%=10;        }                if(dig.front()>=10)//deal carry at the most significant digit        {            dig[0]%=10;//change to one-digit number.            dig.insert(dig.begin(),1);//insert 1 to the front.        }                while(dig.front()==0)//deal with leading zeros.It seems there is no such case.        {            dig.erase(dig.begin());        }        return dig;    }};


1 0
原创粉丝点击