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
- [LeetCode]66.Plus One
- LeetCode --- 66. Plus One
- [Leetcode] 66. Plus One
- [leetcode] 66.Plus One
- 66. Plus One
- 66. Plus One
- [leetcode] 66. Plus One
- Leetcode-66. Plus One
- 【leetcode】66. Plus One
- 66. Plus One
- 66. Plus One LeetCode
- 66. Plus One
- 66. Plus One
- 66. Plus One
- 66. Plus One
- 66. Plus One
- 【LeetCode】66. Plus One
- [LeetCode]66. Plus One
- Linux shell 之 提取文件名和目录名的一些方法
- ListView中同时包含多种布局
- maven 加入json-lib.jar 报错 Missing artifact net.sf.json-lib:json-lib:jar:2.4:compile
- 通知的状况
- TextView支持的Html标签
- 66. Plus One
- JAVA WEB学习——tomcat服务器首页配置
- Contacts的数据存储原理
- MRC && ARC 混编
- 0.2 简单搭建C语言环境
- 浅析Java中的final关键字
- php函数,伪函数的使用:函数名长,会影响到性能?
- 企业版Oracle 11g服务器安装详细步骤——图文教程
- unity中的Transform类