15算法课程 66. Plus One
2017-10-05 20:45
316 查看
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.
solution:
一个用数组表示的整数,数组的每一个元素代表这个整数的一位数字,求这个整数加1之后所代表的数组
code:
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.
solution:
一个用数组表示的整数,数组的每一个元素代表这个整数的一位数字,求这个整数加1之后所代表的数组
code:
class Solution { public: vector<int> plusOne(vector<int>& digits) { vector<int> result; int flag = 1; for (int i = digits.size() - 1; i >= 0; i--) { if (digits[i] == 9 && flag == 1) { result.push_back(0); flag = 1; } if (digits[i] != 9 && flag == 1) { flag = 0; result.push_back(digits[i] + 1); continue; } if (flag == 0) { result.push_back(digits[i]); } } if (flag == 1) { result.push_back(1); } reverse(result.begin(), result.end()); return result; } };
相关文章推荐
- 15算法课程 232. Implement Queue using Stacks
- 15算法课程 101. Symmetric Tree
- 15算法课程 242. Valid Anagram
- 15算法课程 104. Maximum Depth of Binary Tree
- 15算法课程 257. Binary Tree Paths
- 15算法课程 189. Rotate Array
- 15算法课程 21. Merge Two Sorted Lists
- 15算法课程 38. Count and Say
- 15算法课程 234. Palindrome Linked List
- 15算法课程 258. Add Digits
- 15算法课程 190. Reverse Bits
- 15算法课程 292. Nim Game
- 15算法课程 7. Reverse Integer
- 15算法课程 53. Maximum Subarray
- 15算法课程 107. Binary Tree Level Order Traversal II
- 15算法课程 303. Range Sum Query - Immutable
- 15算法课程 9. Palindrome Number
- 15算法课程 191. Number of 1 Bits
- 15算法课程 27. Remove Element
- 15算法课程 58. Length of Last Word