leetcode 66: Plus One
2016-01-05 23:41
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.
思路:
一开始没读懂题目o(╯□╰)o。试了一次题目的测试后才知道,一个个 digit 放进数组里,组成一个非负整数,然后加 1 求结果。看懂题目后就很容易了,基本难点就是操作进位,特别是在最高位需要插入时,可能会造成一些 iterator 的
incompatible错误或是
not decrementable的错误,前者可能是因为 vector 容器内存重新分配造成的,经过一些插入或删除的操作后再使用之前在用的迭代器,很可能出错;后者可能是因为已经来到容器头部或尾部而继续往下操作出现错误。
代码:
class Solution { public: vector<int> plusOne(vector<int>& digits) { vector<int>::reverse_iterator rit = digits.rbegin(); *rit += 1; for (; rit != digits.rend(); rit++) { if (*rit > 9) { int temp = *rit; *rit = temp % 10; if (rit + 1 != digits.rend()) { *(rit + 1) += 1; } else { digits.insert(digits.begin(), 1); break; } } } return digits; } };
相关文章推荐
- bzoj3172【TJOI2013】单词
- xsl与xml转换示例
- Meteor:关闭所有tab时退出登录
- lesson1:Python 判断表达式应用
- maven是什么?(转自oracle官网)
- Java延迟初始化的2种经典模式
- Spark MLlib 包
- mysql 5.7 忘记密码,及修改密码问题,密码列不再是Password ,而是authentication_string
- UITableView的简单使用
- 单个电脑上进行多ssh-key配置
- RDD容错
- svnversion 不是内部命令或外部命令,也不是可运行的程序或批处理文件
- 让手机访问电脑的tomcat
- 数据库006
- SQL学习(二)
- 数据库之基础6
- RDD类操作说明
- Latex宏包管理
- Latex宏包管理
- Latex宏包管理