66-PlusOne
来源:互联网 发布:最新矩阵 编辑:程序博客网 时间:2024/04/29 10:59
难度:easy
题目描述
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
算法分析
(1)尾部+1
(2)尾部加1后没有进位,直接得到结果
(3)循环进位,for循环实现
(4)首位特殊处理,如果首位需要进位,需要重新声明一个vector用于存储结果
代码实现
class Solution {public: vector<int> plusOne(vector<int>& digits) { int n = digits.size(); digits[n - 1] += 1; // 没有进位 if (digits[n - 1] < 10) return digits; for (int i = n - 2; i >= 0; --i) { digits[i] += digits[i + 1] / 10; digits[i + 1] %= 10; } // 首位没有出现进位 if (digits[0] < 10) return digits; // 首位需要进位 vector<int> result; result.push_back(1); digits[0] %= 10; for (int i = 0; i < n; ++i) { result.push_back(digits[i]); } return result; }};
阅读全文
0 0
- 66-PlusOne
- 【Leetcode】PlusOne #66
- <LeetCode><Easy> 66 PlusOne
- PlusOne
- PlusOne
- plusOne
- PlusOne
- plusone
- Leetcode——66 plusOne
- leetcode66.PlusOne
- LintCode PlusOne 加一
- LeetCode之PlusONE
- PlusOne 加一
- LetCode PlusOne的三种解法
- 66
- 66
- 66
- 66
- 解决chrome主页被duba劫持问题
- 公众号编辑器文章代码,写入到自己的web服务器数据库
- unityShader之向量
- 第22节项目6-定期存款利息计算器
- Git使用教程
- 66-PlusOne
- mysql常用指令
- Spring(4):log4j打印日志
- 1A
- numpy.random.randint() 简介
- 阿里云部署 nodejs+mongoDB 傻瓜教程
- 思维转换:蚂蚁问题
- Mac上配置adb
- 树链剖分